Nikhil Sawal
Nikhil Sawal

Reputation: 59

Is there a Matplotlib hack to plot time series data continuously with missing hourly data?

I am trying to plot stock prices data which collected hourly from 8:00 am to 4:00 pm on working days. Now because the market is closed from 4:00 pm to 8:00 am, when I try to plot this series there are long straight lines in between. Is there a hack Matplotlib hack to remove these lines and plot the data continuously?

Following snippet shows the point where there break between days.

               date   price
2021-01-01 08:00:03  338.50
2021-01-01 09:00:02  338.50
2021-01-01 10:00:03  338.50
2021-01-01 11:00:03  338.50
2021-01-01 12:00:02  338.50
2021-01-01 13:00:02  338.50
2021-01-01 14:00:02  338.50
2021-01-01 15:00:03  338.50
2021-01-01 16:00:02  338.50 <------ Break
2021-01-04 08:00:04  338.50
2021-01-04 09:00:06  335.61
2021-01-04 10:02:09  332.08
2021-01-04 11:00:05  331.11
2021-01-04 12:00:40  330.78
2021-01-04 13:00:03  331.93
2021-01-04 14:00:03  333.00
2021-01-04 15:00:04  334.59
2021-01-04 16:00:03  334.59

Following image shows the gaps that I want to remove!

enter image description here

Tried to plot them iteratively as follows. The step size 9 in the following script is the number of working hours per day from 8:00 am - 16:00 pm

for i in range(0, 72, 9):
    plt.plot(uber_df['date'][i:i+9], uber_df['price'][i:i+9])
plt.show()

got the following plot: enter image description here

Upvotes: 1

Views: 1219

Answers (1)

pakpe
pakpe

Reputation: 5489

You can get rid of the gaps if your x-axis had ordered categorical (ordinal) variables. One way of achieving this is to convert the datetime objects in your 'date' column to strings:

df['date'] = df['date'].astype(str)
df = df.set_index('date')

df.plot()
plt.gcf().autofmt_xdate()
plt.show()

Upvotes: 1

Related Questions