Changing the formatting of a datetime axis in matplotlib Changing the formatting of a datetime axis in matplotlib python python

Changing the formatting of a datetime axis in matplotlib


import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport matplotlib.dates as mdates# sample dataN = 30drange = pd.date_range("2014-01", periods=N, freq="MS")np.random.seed(365)  # for a reproducible example of valuesvalues = {'values':np.random.randint(1,20,size=N)}df = pd.DataFrame(values, index=drange)fig, ax = plt.subplots()ax.plot(df.index, df.values)ax.set_xticks(df.index)# use formatters to specify major and minor ticksax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m"))ax.xaxis.set_minor_formatter(mdates.DateFormatter("%Y-%m"))_ = plt.xticks(rotation=90)    

enter image description here


You can try something like this:

import matplotlib.dates as mdatesimport matplotlib.pyplot as pltdf = pd.DataFrame({'values':np.random.randint(0,1000,36)},index=pd.date_range(start='2014-01-01',end='2016-12-31',freq='M'))fig,ax1 = plt.subplots()plt.plot(df.index,df.values)monthyearFmt = mdates.DateFormatter('%Y %B')ax1.xaxis.set_major_formatter(monthyearFmt)_ = plt.xticks(rotation=90)

enter image description here