[英]How to format Matplotlib secondary y-axis datetime values
I am attempting to plot a line graph superimposed on a bar graph using matplotlib. 我正在尝试使用matplotlib绘制叠加在条形图上的折线图。 The data has plotted correctly, however, the secondary y-axis describing the forecasted start time is being output incorrectly. 数据已正确绘制,但是描述预测开始时间的辅助y轴输出错误。 All values for Forecasted Start Time are rounded off to the hour eg (13:00, 14:00, etc) but when plotted are converted to 11:40, 12:13:20, etc on the y-axis, as so: “预测的开始时间”的所有值均四舍五入为小时,例如(13:00、14:00等),但是在绘制时会在y轴上转换为11:40、12:13:20等,如下所示:
Forecasted Start Time csv data 预测开始时间CSV数据
Forecasted Start Time and Event Length vs. Forecast Run graph 预测开始时间和事件长度与预测运行图
The code to produce this image is as follows: 产生该图像的代码如下:
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()
Any ideas on how to plot the actual datetime values from the csv correctly on the secondary y-axis would be greatly appreciated! 任何有关如何在辅助y轴上正确绘制csv的实际datetime值的想法,将不胜感激!
You need to plot on the axis object using ax.bar
and ax2.plot
instead of plt.bar
and plt.plot
. 您需要使用ax.bar
和ax2.plot
而不是plt.bar
和plt.plot
在轴对象上进行plt.plot
。
You can use the axis formatter to do this: 您可以使用轴格式化程序来执行此操作:
from matplotlib.dates import DateFormatter
ax2.yaxis.set_major_locator(md.HourLocator(interval=1))
ax2.yaxis.set_major_formatter(md.DateFormatter('%H:%M'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.