1

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

  • Maybe you could make a procedure in which you find which element in your data represents the end of the first day. Subsequently, you plot all data from the first element to the element representing the end of the first day. Then, you start from one element past the end of the first day and find the element representing the end of the second day. You could repeat this procedure until you have reached the end of your data. In this way, you'd no longer have connections between the lines representing different days. – DeX97 Mar 06 '21 at 17:56
  • Hey i tried that! Got rid of the lines but still have the gaps. I will put sample image in my main question for your reference – Nikhil Sawal Mar 06 '21 at 23:18

1 Answers1

1

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()
pakpe
  • 5,391
  • 2
  • 8
  • 23