python - Matplotlib: Making a line graph's datetime x axis labels look like Excel -
i have simple pandas dataframe yearly values plotting line graph:
import matplotlib.pyplot plt import pandas pd  >>>df               b 2010-01-01  9.7 9.0 2011-01-01  8.8 14.2 2012-01-01  8.4 7.6 2013-01-01  9.6 8.4 2014-01-01  8.2 5.5   the expected format x axis use no margins labels:
fig  = plt.figure(0) ax = fig.add_subplot(1, 1, 1) df.plot(ax = ax)   
but force values plot in middle of year range, done in excel:

i have tried setting x axis margins:
ax.margins(xmargin = 1)   but can see no difference.
if want move dates, try adding line @ end:
ax.set_xlim(ax.get_xlim()[0] - 0.5, ax.get_xlim()[1] + 0.5)    if need format dates either modify index or make changes in plotted ticks so: (presuming df.index datetime object) 
ax.set_xticklabels(df.index.to_series().apply(lambda x: x.strftime('%d/%m/%y')))   this format dates excel example.
or change index want , call .plot():
df.index = df.index.to_series().apply(lambda x: x.strftime('%d/%m/%y')) print df.index.tolist()  ['01/01/2010', '01/01/2011', '01/01/2012', '01/01/2013', '01/01/2014']   and, if index not datetime need convert first this:
df.index = pd.to_datetime(df.index)      
Comments
Post a Comment