Search code examples
pythonmatplotlibplottime-seriestimeserieschart

Plot time series by hour in the same plot with Matplotlib and Pandas


I have a time series containing timestamps with the format '2017-04-01 00:00:00'; the time series contains roughly 30 days worth of data.

In order to get a visual idea of the variability of this series I would like to plot it as a function of the hour of the day and have all days superposed on the same plot. In this way the horizontal axis would range from 00:00:00 to 23:45:00, and I would be able to see what is the variability of the series for any particular time of the day as specified by the timestamp.

My time series is stored in a Pandas data frame and I am using Matplotlib. Could someone please tell me if there is a way to do this?


Solution

  • I'd suggest you to loop over your df, constitute arrays per day and plot them on the fly.

    previous_day = dataframe[0]['date'].day
    daily_data = []
    daily_times = []
    
    for row in dataframe:
        if row['date'].day == previous_day:
            daily_data.append(row['data_to_plot'])
            daily_times.append(row['date'])
    
        else:
            plt.plot(daily_times, daily_data)
            previous_day = row['date'].day
            daily_data = []
            daily_times = []
    
    plt.plot(daily_times, daily_data)
    plt.show()
    

    here is the python library to manipulate dates

    here you'll find how to superimpose curves with matplotlib