A1122
A1122

Reputation: 1354

Formatting datetime for plotting time-series with pandas

I am plotting some time-series with pandas dataframe and I ran into the problem of gaps on weekends. What can I do to remove gaps in the time-series plot?

date_concat = pd.to_datetime(pd.Series(df.index),infer_datetime_format=True)
pca_factors.index = date_concat
pca_colnames = ['Outright', 'Curve', 'Convexity']
pca_factors.columns = pca_colnames

fig,axes = plt.subplots(2)
pca_factors.Curve.plot(ax=axes[0]); axes[0].set_title('Curve')
pca_factors.Convexity.plot(ax=axes[1]); axes[1].set_title('Convexity'); plt.axhline(linewidth=2, color = 'g')
fig.tight_layout()
fig.savefig('convexity.png')

Partial plot below: enter image description here

Ideally, I would like the time-series to only show the weekdays and ignore weekends.

Upvotes: 1

Views: 1456

Answers (1)

StarFox
StarFox

Reputation: 637

To make MaxU's suggestion more explicit:

  • convert to datetime as you have done, but drop the weekends
  • reset the index and plot the data via this default Int64Index
  • change the x tick labels

Code:

date_concat = data_concat[date_concat.weekday < 5] # drop weekends
pca_factors = pca_factors.reset_index() # from MaxU's comment
pca_factors['Convexity'].plot()         # ^^^
plt.xticks(pca_factors.index, date_concat) # change the x tick labels

Upvotes: 1

Related Questions