- Create time
there are some situations that we will meet to create time as x-axis. this code means generate a set of time from 1958 to 1991.
time = np.arange('1958', '1991', dtype='datetime64[M]').tolist()
The example of the output of this code is:
[datetime.date(1958, 1, 1), datetime.date(1958, 2, 1), datetime.date(1958, 3, 1), datetime.date(1958, 4, 1), datetime.date(1958, 5, 1), datetime.date(1958, 6, 1), datetime.date(1958, 7, 1), datetime.date(1958, 8, 1), datetime.date(1958, 9, 1), datetime.date(1958, 10, 1), datetime.date(1958, 11, 1), datetime.date(1958, 12, 1), datetime.date(1959, 1, 1), datetime.date(1959, 2, 1), datetime.date(1959, 3, 1), datetime.date(1959, 4, 1), datetime.date(1959, 5, 1), datetime.date(1959, 6, 1), datetime.date(1959, 7, 1), datetime.date(1959, 8, 1), datetime.date(1959, 9, 1), datetime.date(1959, 10, 1), datetime.date(1959, 11, 1), datetime.date(1959, 12, 1), datetime.date(1960, 1, 1), etc]
- Rewrite the representation of the x-axis
We have figured out how to generate time for the month, but now we want to display the year on the x-axis.
ax.xaxis.set_major_formatter(mdate.DateFormatter('%Y'))
this code can make it can also we can change the parameter into ‘%Y%M%D’ to show the month or day.
- the number of items on the x-axis
however, we will face a large range of time, but we only want show some of them
ax.xaxis.set_major_locator(plt.MaxNLocator(10)) # Show 10 ticks on the x-axis
this code will be help that means only show 10 ticks on the x-axis.
to make it x-axis more visually appealing. we can rotate the ticks like this code.
plt.xticks(rotation=45)