How to set two time formatters in matplotlib?

孤者浪人 提交于 2021-02-15 05:26:22

问题


This chart is built by Excel. 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:


回答1:


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:

  • primary hours, secondary minutes
  • primary months, secondary days


来源:https://stackoverflow.com/questions/62612963/how-to-set-two-time-formatters-in-matplotlib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!