如何格式化 Matplotlib 辅助 y 轴日期时间值
How to format Matplotlib secondary y-axis datetime values
我正在尝试使用 matplotlib 绘制叠加在条形图上的折线图。数据已正确绘制,但是,描述预测开始时间的辅助 y 轴输出不正确。 Forecasted Start Time 的所有值都四舍五入到小时,例如(13:00, 14:00, etc) 但绘制时在 y 轴上转换为 11:40, 12:13:20, 等,如下所示:
Forecasted Start Time csv data
Forecasted Start Time and Event Length vs. Forecast Run graph
生成这张图片的代码如下:
en1 = []
en2 =[]
en1 = np.array(fh.loc(axis=0)[0:44])
en2 = np.array(ev.loc(axis=0)[0:44])
fig,ax = plt.subplots(figsize=(10,10))
ax.bar(en1,en2,color='gainsboro')
plt.ylabel('Forecasted Event Length')
plt.xticks(rotation='90')
ax2 = ax.twinx()
mn, mx = ax2.get_ylim()
ax2.set_ylabel('Forecasted Start Time')
color = 'tab:blue'
ax2.tick_params(axis='y')
ax2.plot(fh,start, marker='o')
plt.legend()
如有任何关于如何在辅助 y 轴上正确绘制 csv 中的实际日期时间值的想法,我们将不胜感激!
您需要使用 ax.bar
和 ax2.plot
而不是 plt.bar
和 plt.plot
在轴对象上绘制。
您可以使用轴格式化程序来执行此操作:
from matplotlib.dates import DateFormatter
ax2.yaxis.set_major_locator(md.HourLocator(interval=1))
ax2.yaxis.set_major_formatter(md.DateFormatter('%H:%M'))
我正在尝试使用 matplotlib 绘制叠加在条形图上的折线图。数据已正确绘制,但是,描述预测开始时间的辅助 y 轴输出不正确。 Forecasted Start Time 的所有值都四舍五入到小时,例如(13:00, 14:00, etc) 但绘制时在 y 轴上转换为 11:40, 12:13:20, 等,如下所示:
Forecasted Start Time csv data
Forecasted Start Time and Event Length vs. Forecast Run graph
生成这张图片的代码如下:
en1 = []
en2 =[]
en1 = np.array(fh.loc(axis=0)[0:44])
en2 = np.array(ev.loc(axis=0)[0:44])
fig,ax = plt.subplots(figsize=(10,10))
ax.bar(en1,en2,color='gainsboro')
plt.ylabel('Forecasted Event Length')
plt.xticks(rotation='90')
ax2 = ax.twinx()
mn, mx = ax2.get_ylim()
ax2.set_ylabel('Forecasted Start Time')
color = 'tab:blue'
ax2.tick_params(axis='y')
ax2.plot(fh,start, marker='o')
plt.legend()
如有任何关于如何在辅助 y 轴上正确绘制 csv 中的实际日期时间值的想法,我们将不胜感激!
您需要使用 ax.bar
和 ax2.plot
而不是 plt.bar
和 plt.plot
在轴对象上绘制。
您可以使用轴格式化程序来执行此操作:
from matplotlib.dates import DateFormatter
ax2.yaxis.set_major_locator(md.HourLocator(interval=1))
ax2.yaxis.set_major_formatter(md.DateFormatter('%H:%M'))