1

How can I have the dates on the x-axis displayed as months, e.g. 'Jan', 'Feb'...'Dec'. instead of 2015-01, 2015-02,etc. I'm reproducing a shortened version of my df.

MyPlot

I have read https://matplotlib.org/examples/api/date_demo.html and not sure how to apply it to my data.

Or, maybe when I'm mapping the dates to pd.to_datetime, I could somehow convert them to months only using ' %b' for the month names? Or could use something along these lines,pd.date_range('2015-01-01','2016-01-01', freq='MS').strftime("%b").tolist(), in xticks? Thank you!

import matplotlib.pyplot as plt

df1 = pd.DataFrame({'Date':['2015-01-01','2015-01-02','2015-01-03','2015-01-04','2015-01-05'],'Values':[-13.3,-12.2,6.7,8.8,15.5]})
df1.Date=pd.to_datetime(df1.Date)
df1['Day']=pd.DatetimeIndex(df1['Date']).day
df1['Month']=pd.DatetimeIndex(df1['Date']).month
df1=df1[['Month','Day','Values']]
df1

df2=pd.DataFrame({'Date':['2015-01-01','2015-01-02','2015-01-03','2015-01-04','2015-01-05'],'Values':[-5.6,-5.6,0,3.9,9.4]})
df2['Day']=pd.DatetimeIndex(df2['Date']).day
df2['Month']=pd.DatetimeIndex(df2['Date']).month
df2=df2[['Month','Day','Values']]
df2

plt.figure(figsize=(10,6))

ax = plt.gca()
dates = np.arange('2015-01-01', '2015-01-06', dtype='datetime64[D]')
dates=list(map(pd.to_datetime, dates))
plt.plot(dates, df1.Values, '-^',dates, df2.Values, '-o')

ax.set_xlim(dates[0],dates[4])

x = plt.gca().xaxis

for item in x.get_ticklabels():
    item.set_rotation(45)

plt.show()
Bluetail
  • 1,093
  • 2
  • 13
  • 27
  • IMHO, you are doing too much processing with `df2['Day']=pd.DatetimeIndex(df2['Date']).day`, etc... Unless your input data are such, in which case, you should combine the `month` and `day` back into `Date`. – Quang Hoang Apr 27 '20 at 20:59
  • I had to pre-process this data to remove certain dates in a month, that is why 'month' and 'day' are left. I could possibly convert them to Date again. however, I'm only using the 'Values' column from the two dataframes? – Bluetail Apr 27 '20 at 21:26
  • and if I combine them back into into Date, how should I proceed? thank you sir. – Bluetail Apr 27 '20 at 23:15

1 Answers1

0

I have arrived at the following solution:

ax.xaxis.set_major_formatter(mdates.DateFormatter('%b'))

perhaps, someone has a better one.

Bluetail
  • 1,093
  • 2
  • 13
  • 27