为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

ITMISS 2023-02-07 17:26:51
此图表由 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)它绘制:
查看完整描述

1 回答

?
慕少森

TA贡献2019条经验 获得超9个赞

您应该为标签使用辅助轴year,同时为标签使用主要轴month。您可以使用以下内容生成辅助轴:


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]])


查看完整回答
反对 回复 2023-02-07
  • 1 回答
  • 0 关注
  • 80 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信