0

I have this following df :

date                  values
2020-08-06 08:00:00   5
2020-08-06 09:00:00   10
2020-08-06 10:00:00   0
2020-08-17 08:00:00   8
2020-08-17 09:00:00   15

I want to plot this df so I do : df.set_index('date')['values'].plot(kind='line') but it shows all the dates between the 6th and the 17th.

How can I plot the graph only with the dates inside my df ?

Pi-R
  • 644
  • 3
  • 10

1 Answers1

0

I assume that date column is of datetime type.

To draw for selected dates only, the index must be built on the principle "number of day from a unique list + hour".

But to suppress the default x label ticks, you have to define your own, e.g. each 8 h in each date to be drawn.

Start from converting your DataFrame as follows:

idx = df['date'].dt.normalize().unique()
dateMap = pd.Series(np.arange(idx.size) * 24, index=idx)
df.set_index(df.date.dt.date.map(dateMap) + df.date.dt.hour, inplace=True)
df.index.rename('HourNo', inplace=True); df

Now, for your data sample, it has the following content:

                      date  values
HourNo                            
8      2020-08-06 08:00:00       5
9      2020-08-06 09:00:00      10
10     2020-08-06 10:00:00       0
32     2020-08-17 08:00:00       8
33     2020-08-17 09:00:00      15

Then generate your plot and x ticks positions and labels:

fig, ax = plt.subplots(tight_layout=True)
df.loc[:, 'values'].plot(style='o-', rot=30, ax=ax)
xLoc = np.arange(0, dateMap.index.size * 24, 8)
xLbl = pd.concat([ pd.Series(d + pd.timedelta_range(start=0, freq='8H',
    periods=3)) for d in dateMap.index ]).dt.strftime('%Y-%m-%d\n%H:%M')
plt.xticks(ticks=xLoc, labels=xLbl, ha='right')
ax.set_xlabel('Date')
ax.set_ylabel('Value')
ax.set_title('Set the proper heading')
ax.grid()
plt.show()

I added also the grid.

The result is:

enter image description here

And the final remark: Avoid column names which are the same as existing Pandas methods or arrtibutes (e.g. values). Sometimes it is the cause of "stupid" errors (you intend to refer to a column, but you actually refer to a metod or attribute).

Valdi_Bo
  • 30,023
  • 4
  • 23
  • 41