Pandas plotting--ignore time range










2















Let's say I have one-minute data during business hours of 8am to 4pm over three days. I would like to plot these data using the pandas plot function:



import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(51723)
dates = pd.date_range("11/8/2018", "11/11/2018", freq = "min")
df = pd.DataFrame(np.random.rand(len(dates)), index = dates, columns = ['A'])
df = df[(df.index.hour >= 8) & (df.index.hour <= 16)] # filter for business hours

fig, ax = plt.subplots()
df.plot(ax = ax)
plt.show()


However, the plot function also includes overnight hours in the plot, resulting in unintended plotting during this time:



bad plotting



I would the data to be plotted contiguously, ignoring the overnight time (something like this):
good plotting



What is a good way to plot only the intended hours of 8am to 4pm?










share|improve this question
























  • How about set those value to 0?

    – Q. Qiao
    Nov 12 '18 at 17:41











  • @Q.Qiao there are actually no values in the (filtered) dataframe for the overnight hours, but the plot function "connects the dots" between 4pm one day and 8am the next. I would like the plot function to just ignore the overnight time and not plot the connected line (or anything in that time period)

    – bcf
    Nov 12 '18 at 17:45











  • there are two ways, either you pad your data with 0 values until the line you circled is stuck to the OX axis or you make a separate figure for each day.

    – vencaslac
    Nov 12 '18 at 17:46











  • your x-axis is now datetime. You can make that numerical and add the datetime labels

    – hootnot
    Nov 12 '18 at 17:46











  • see, for example: stackoverflow.com/questions/10529492/…

    – hootnot
    Nov 12 '18 at 17:52















2















Let's say I have one-minute data during business hours of 8am to 4pm over three days. I would like to plot these data using the pandas plot function:



import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(51723)
dates = pd.date_range("11/8/2018", "11/11/2018", freq = "min")
df = pd.DataFrame(np.random.rand(len(dates)), index = dates, columns = ['A'])
df = df[(df.index.hour >= 8) & (df.index.hour <= 16)] # filter for business hours

fig, ax = plt.subplots()
df.plot(ax = ax)
plt.show()


However, the plot function also includes overnight hours in the plot, resulting in unintended plotting during this time:



bad plotting



I would the data to be plotted contiguously, ignoring the overnight time (something like this):
good plotting



What is a good way to plot only the intended hours of 8am to 4pm?










share|improve this question
























  • How about set those value to 0?

    – Q. Qiao
    Nov 12 '18 at 17:41











  • @Q.Qiao there are actually no values in the (filtered) dataframe for the overnight hours, but the plot function "connects the dots" between 4pm one day and 8am the next. I would like the plot function to just ignore the overnight time and not plot the connected line (or anything in that time period)

    – bcf
    Nov 12 '18 at 17:45











  • there are two ways, either you pad your data with 0 values until the line you circled is stuck to the OX axis or you make a separate figure for each day.

    – vencaslac
    Nov 12 '18 at 17:46











  • your x-axis is now datetime. You can make that numerical and add the datetime labels

    – hootnot
    Nov 12 '18 at 17:46











  • see, for example: stackoverflow.com/questions/10529492/…

    – hootnot
    Nov 12 '18 at 17:52













2












2








2








Let's say I have one-minute data during business hours of 8am to 4pm over three days. I would like to plot these data using the pandas plot function:



import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(51723)
dates = pd.date_range("11/8/2018", "11/11/2018", freq = "min")
df = pd.DataFrame(np.random.rand(len(dates)), index = dates, columns = ['A'])
df = df[(df.index.hour >= 8) & (df.index.hour <= 16)] # filter for business hours

fig, ax = plt.subplots()
df.plot(ax = ax)
plt.show()


However, the plot function also includes overnight hours in the plot, resulting in unintended plotting during this time:



bad plotting



I would the data to be plotted contiguously, ignoring the overnight time (something like this):
good plotting



What is a good way to plot only the intended hours of 8am to 4pm?










share|improve this question
















Let's say I have one-minute data during business hours of 8am to 4pm over three days. I would like to plot these data using the pandas plot function:



import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(51723)
dates = pd.date_range("11/8/2018", "11/11/2018", freq = "min")
df = pd.DataFrame(np.random.rand(len(dates)), index = dates, columns = ['A'])
df = df[(df.index.hour >= 8) & (df.index.hour <= 16)] # filter for business hours

fig, ax = plt.subplots()
df.plot(ax = ax)
plt.show()


However, the plot function also includes overnight hours in the plot, resulting in unintended plotting during this time:



bad plotting



I would the data to be plotted contiguously, ignoring the overnight time (something like this):
good plotting



What is a good way to plot only the intended hours of 8am to 4pm?







python pandas matplotlib






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 12 '18 at 18:00







bcf

















asked Nov 12 '18 at 17:39









bcfbcf

9281128




9281128












  • How about set those value to 0?

    – Q. Qiao
    Nov 12 '18 at 17:41











  • @Q.Qiao there are actually no values in the (filtered) dataframe for the overnight hours, but the plot function "connects the dots" between 4pm one day and 8am the next. I would like the plot function to just ignore the overnight time and not plot the connected line (or anything in that time period)

    – bcf
    Nov 12 '18 at 17:45











  • there are two ways, either you pad your data with 0 values until the line you circled is stuck to the OX axis or you make a separate figure for each day.

    – vencaslac
    Nov 12 '18 at 17:46











  • your x-axis is now datetime. You can make that numerical and add the datetime labels

    – hootnot
    Nov 12 '18 at 17:46











  • see, for example: stackoverflow.com/questions/10529492/…

    – hootnot
    Nov 12 '18 at 17:52

















  • How about set those value to 0?

    – Q. Qiao
    Nov 12 '18 at 17:41











  • @Q.Qiao there are actually no values in the (filtered) dataframe for the overnight hours, but the plot function "connects the dots" between 4pm one day and 8am the next. I would like the plot function to just ignore the overnight time and not plot the connected line (or anything in that time period)

    – bcf
    Nov 12 '18 at 17:45











  • there are two ways, either you pad your data with 0 values until the line you circled is stuck to the OX axis or you make a separate figure for each day.

    – vencaslac
    Nov 12 '18 at 17:46











  • your x-axis is now datetime. You can make that numerical and add the datetime labels

    – hootnot
    Nov 12 '18 at 17:46











  • see, for example: stackoverflow.com/questions/10529492/…

    – hootnot
    Nov 12 '18 at 17:52
















How about set those value to 0?

– Q. Qiao
Nov 12 '18 at 17:41





How about set those value to 0?

– Q. Qiao
Nov 12 '18 at 17:41













@Q.Qiao there are actually no values in the (filtered) dataframe for the overnight hours, but the plot function "connects the dots" between 4pm one day and 8am the next. I would like the plot function to just ignore the overnight time and not plot the connected line (or anything in that time period)

– bcf
Nov 12 '18 at 17:45





@Q.Qiao there are actually no values in the (filtered) dataframe for the overnight hours, but the plot function "connects the dots" between 4pm one day and 8am the next. I would like the plot function to just ignore the overnight time and not plot the connected line (or anything in that time period)

– bcf
Nov 12 '18 at 17:45













there are two ways, either you pad your data with 0 values until the line you circled is stuck to the OX axis or you make a separate figure for each day.

– vencaslac
Nov 12 '18 at 17:46





there are two ways, either you pad your data with 0 values until the line you circled is stuck to the OX axis or you make a separate figure for each day.

– vencaslac
Nov 12 '18 at 17:46













your x-axis is now datetime. You can make that numerical and add the datetime labels

– hootnot
Nov 12 '18 at 17:46





your x-axis is now datetime. You can make that numerical and add the datetime labels

– hootnot
Nov 12 '18 at 17:46













see, for example: stackoverflow.com/questions/10529492/…

– hootnot
Nov 12 '18 at 17:52





see, for example: stackoverflow.com/questions/10529492/…

– hootnot
Nov 12 '18 at 17:52












1 Answer
1






active

oldest

votes


















0














This can be done by plotting each date on a different axis. But things like the labels will get cramped in certain cases.



import datetime
import matplotlib.pyplot as plt

pdates = np.unique(df.index.date) # Unique Dates

fig, ax = plt.subplots(ncols=len(pdates), sharey=True, figsize=(18,6))

# Adjust spacing between suplots
# (Set to 0 for continuous, though labels will overlap)
plt.subplots_adjust(wspace=0.05)

# Plot all data on each subplot, adjust the limits of each accordingly
for i in range(len(pdates)):
df.plot(ax=ax[i], legend=None)
# Hours 8-16 each day:
ax[i].set_xlim(datetime.datetime.combine(pdates[i], datetime.time(8)),
datetime.datetime.combine(pdates[i], datetime.time(16)))

# Deal with spines for each panel
if i !=0:
ax[i].spines['left'].set_visible(False)
ax[i].tick_params(right=False,
which='both',
left=False,
axis='y')
if i != len(pdates)-1:
ax[i].spines['right'].set_visible(False)
plt.show()


enter image description here






share|improve this answer






















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53267385%2fpandas-plotting-ignore-time-range%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    This can be done by plotting each date on a different axis. But things like the labels will get cramped in certain cases.



    import datetime
    import matplotlib.pyplot as plt

    pdates = np.unique(df.index.date) # Unique Dates

    fig, ax = plt.subplots(ncols=len(pdates), sharey=True, figsize=(18,6))

    # Adjust spacing between suplots
    # (Set to 0 for continuous, though labels will overlap)
    plt.subplots_adjust(wspace=0.05)

    # Plot all data on each subplot, adjust the limits of each accordingly
    for i in range(len(pdates)):
    df.plot(ax=ax[i], legend=None)
    # Hours 8-16 each day:
    ax[i].set_xlim(datetime.datetime.combine(pdates[i], datetime.time(8)),
    datetime.datetime.combine(pdates[i], datetime.time(16)))

    # Deal with spines for each panel
    if i !=0:
    ax[i].spines['left'].set_visible(False)
    ax[i].tick_params(right=False,
    which='both',
    left=False,
    axis='y')
    if i != len(pdates)-1:
    ax[i].spines['right'].set_visible(False)
    plt.show()


    enter image description here






    share|improve this answer



























      0














      This can be done by plotting each date on a different axis. But things like the labels will get cramped in certain cases.



      import datetime
      import matplotlib.pyplot as plt

      pdates = np.unique(df.index.date) # Unique Dates

      fig, ax = plt.subplots(ncols=len(pdates), sharey=True, figsize=(18,6))

      # Adjust spacing between suplots
      # (Set to 0 for continuous, though labels will overlap)
      plt.subplots_adjust(wspace=0.05)

      # Plot all data on each subplot, adjust the limits of each accordingly
      for i in range(len(pdates)):
      df.plot(ax=ax[i], legend=None)
      # Hours 8-16 each day:
      ax[i].set_xlim(datetime.datetime.combine(pdates[i], datetime.time(8)),
      datetime.datetime.combine(pdates[i], datetime.time(16)))

      # Deal with spines for each panel
      if i !=0:
      ax[i].spines['left'].set_visible(False)
      ax[i].tick_params(right=False,
      which='both',
      left=False,
      axis='y')
      if i != len(pdates)-1:
      ax[i].spines['right'].set_visible(False)
      plt.show()


      enter image description here






      share|improve this answer

























        0












        0








        0







        This can be done by plotting each date on a different axis. But things like the labels will get cramped in certain cases.



        import datetime
        import matplotlib.pyplot as plt

        pdates = np.unique(df.index.date) # Unique Dates

        fig, ax = plt.subplots(ncols=len(pdates), sharey=True, figsize=(18,6))

        # Adjust spacing between suplots
        # (Set to 0 for continuous, though labels will overlap)
        plt.subplots_adjust(wspace=0.05)

        # Plot all data on each subplot, adjust the limits of each accordingly
        for i in range(len(pdates)):
        df.plot(ax=ax[i], legend=None)
        # Hours 8-16 each day:
        ax[i].set_xlim(datetime.datetime.combine(pdates[i], datetime.time(8)),
        datetime.datetime.combine(pdates[i], datetime.time(16)))

        # Deal with spines for each panel
        if i !=0:
        ax[i].spines['left'].set_visible(False)
        ax[i].tick_params(right=False,
        which='both',
        left=False,
        axis='y')
        if i != len(pdates)-1:
        ax[i].spines['right'].set_visible(False)
        plt.show()


        enter image description here






        share|improve this answer













        This can be done by plotting each date on a different axis. But things like the labels will get cramped in certain cases.



        import datetime
        import matplotlib.pyplot as plt

        pdates = np.unique(df.index.date) # Unique Dates

        fig, ax = plt.subplots(ncols=len(pdates), sharey=True, figsize=(18,6))

        # Adjust spacing between suplots
        # (Set to 0 for continuous, though labels will overlap)
        plt.subplots_adjust(wspace=0.05)

        # Plot all data on each subplot, adjust the limits of each accordingly
        for i in range(len(pdates)):
        df.plot(ax=ax[i], legend=None)
        # Hours 8-16 each day:
        ax[i].set_xlim(datetime.datetime.combine(pdates[i], datetime.time(8)),
        datetime.datetime.combine(pdates[i], datetime.time(16)))

        # Deal with spines for each panel
        if i !=0:
        ax[i].spines['left'].set_visible(False)
        ax[i].tick_params(right=False,
        which='both',
        left=False,
        axis='y')
        if i != len(pdates)-1:
        ax[i].spines['right'].set_visible(False)
        plt.show()


        enter image description here







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 12 '18 at 19:28









        ALollzALollz

        11.8k31436




        11.8k31436



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53267385%2fpandas-plotting-ignore-time-range%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Use pre created SQLite database for Android project in kotlin

            Darth Vader #20

            Ondo