如何在matplotlib中设置两个时间格式器? [英] How to set two time formatters in matplotlib?

查看:45
本文介绍了如何在matplotlib中设置两个时间格式器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此图表是由Excel构建的.如何使用matplotlib做同样的事情?

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

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

I mean how to add two formatters:

  • 个月.

现在我使用这样的东西:

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)

它绘制:

推荐答案

对于 year 标签,应使用辅助轴,对于 month 标签,应使用辅助轴..您可以使用以下内容生成辅助轴:

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

最后绘制并使用 md.MonthLocator md.YearLocator 调整主轴和辅助轴的格式.像这样的东西应该没问题:

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:

这篇关于如何在matplotlib中设置两个时间格式器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆