Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
717 views
in Technique[技术] by (71.8m points)

python - How to set two time formatters in matplotlib?

This chart is built by Excel. enter image description here How can I do the same using matplotlib?

I mean how to add two formatters:

  • years
  • months.

Now i use something like this:

fig, ax = plt.subplots(1,1)
ax.margins(x=0)
ax.plot(list(df['Date']), list(df['Value']), color="g")
ax.xaxis.set_major_locator(matplotlib.dates.YearLocator())
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%Y'))
plt.text(df["Date"].iloc[-1], df["Value"].iloc[-1], df["Value"].iloc[-1])
plt.title(title)
plt.get_current_fig_manager().full_screen_toggle()
plt.grid(axis = 'y')
plt.savefig('pict\'+sheet.cell_value(row,1).split(',')[0]+'.png', dpi=300, format='png')
#plt.show()
plt.close(fig)

It draws:

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should use a secondary axis for the year labels, while using the primary for the month label. You can generate a secondary axis with something like:

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
import matplotlib.dates as md

fig = plt.figure()
months = host_subplot(111, axes_class = AA.Axes, figure = fig)
plt.subplots_adjust(bottom = 0.1)
years = months.twiny()

Then you should move the secondary axis to the bottom with:

offset = -20
new_fixed_axis = years.get_grid_helper().new_fixed_axis
years.axis['bottom'] = new_fixed_axis(loc = 'bottom',
                                      axes = years,
                                      offset = (0, offset))

Finally you plot and then adjust the primary and secondary axes format with md.MonthLocator and md.YearLocator. Something like this should be fine:

months.xaxis.set_major_locator(md.MonthLocator(interval = 1))
months.xaxis.set_major_formatter(md.DateFormatter('%B'))
months.set_xlim([df['Date'].iloc[0], df['Date'].iloc[-1]])

years.xaxis.set_major_locator(md.YearLocator(interval = 1))
years.xaxis.set_major_formatter(md.DateFormatter('%H'))
years.set_xlim([df['Date'].iloc[0], df['Date'].iloc[-1]])

Try to check these two answers, it should not be difficult to adapt those codes to your case:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...