How to make the x axis more verbose when working with date_range
I am trying to plot a graph of the monthly data I received. When plotting, the graph only displays the year on the x-axis, not the month. How can I do this, also show the month on the x tick labels?
import pandas as pd
import numpy as np
new_index = pd.date_range(start = "2012-07-01", end = "2017-07-01", freq = "MS")
columns = ['0']
df = pd.DataFrame(index=new_index, columns=columns)
for index, row in df.iterrows():
row[0] = np.random.randint(0,100)
%matplotlib inline
df.loc['2015-09-01'] = np.nan
df.plot(kind="line",title="Data per month", figsize = (40,10), grid=True, fontsize=20)
+3
source to share
1 answer
You can use FixedFormatter
from matplotlib.ticker
to define your own custom tick formatter, like here:
...
ticklabels = [item.strftime('%b %Y') for item in df.index[::6]] # set ticks format: month name and year for every 6 elements of index
plt.gca().xaxis.set_ticks(df.index[::6]) # set new ticks for current x axis
plt.gca().xaxis.set_major_formatter(ticker.FixedFormatter(ticklabels)) # apply new tick format
...
+2
source to share