简体   繁体   中英

How to add monthly labels to x-axis using matplotlib?

For an assignment I need to plot record (min and max) temperatures over the period 2004-2014 using matplotlib. The figure is almost complete (see below) except for the x axis labelling. When plotting, I did not specify the x-axis value so it generated integers from 0-365, thus the number of days in a year. Now I want the months to appear as x-axis labels instead of integers (Jan, Feb, etc.). Can someone help me out?

Record low and high temperatures:

在此处输入图片说明

I generated source data as follows:

np.random.seed(13)
dates = pd.date_range(start='2014-01-01', end='2014-12-31')
temp = pd.DataFrame({'tMin': np.random.normal(0, 0.5, dates.size).cumsum() - 10,
    'tMax': np.random.normal(0, 0.5, dates.size).cumsum() + 10}, index=dates)

To get the picture with month labels, try the following code:

# Imports
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# Drawing
fig, ax = plt.subplots(figsize=(10, 4))
plt.xlabel('Month')
plt.ylabel('Temp')
plt.title('Temperatures 2014')
ax.xaxis.set_major_locator(mdates.MonthLocator())
fmt = mdates.DateFormatter('%b %Y')
ax.xaxis.set_major_formatter(fmt)
ax.plot(temp.tMin)
ax.plot(temp.tMax)
ax.fill_between(temp.index, temp.tMin, temp.tMax, color='#A0E0A0', alpha=0.2) 
plt.setp(ax.get_xticklabels(), rotation=30);

For the above source data I got the following picture:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM