How to make x-axis more detailed when working with date_range

时间:2017-06-15 09:37:05

标签: python pandas matplotlib

I'm trying to plot a diagram of monthly data I received. When plotting the data, the plot only shows the year on the x axis, but not the month. How can I make it also show the month on 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)

enter image description here

1 个答案:

答案 0 :(得分:2)

You may use FixedFormatter from matplotlib.ticker to define your own formatter for custom ticks 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

...

enter image description here

Or dates in two lines if use %b\n%Y format: enter image description here