Python 如何在matplotlib中设置两个时间格式化程序?

Python 如何在matplotlib中设置两个时间格式化程序?,python,pandas,datetime,matplotlib,xticks,Python,Pandas,Datetime,Matplotlib,Xticks,这个图表是用Excel建立的。 如何使用matplotlib执行相同的操作 我的意思是如何添加两个格式化程序: 年头 几个月 现在我使用这样的方法: 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.x

这个图表是用Excel建立的。 如何使用matplotlib执行相同的操作

我的意思是如何添加两个格式化程序:

  • 年头
  • 几个月
现在我使用这样的方法:

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)
它得出:


您应该为
年标签使用次轴,而为
月标签使用主轴。可以生成具有以下内容的次轴:

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()
然后,应使用以下命令将次轴移动到底部:

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))
最后,使用
md.MonthLocator
md.YearLocator
打印并调整主轴和副轴格式。像这样的事情应该可以:

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]])
尝试检查这两个答案,根据您的情况调整这些代码应该不难: