[英]Matplotlib not plotting all data points in bar graph
我正在研究时间序列数据集。 我想要一个销售折线图和一条显示该时间段内平均销售额的水平线。 这部分工作正常。
我想在折线图顶部添加一个条形图,显示销售额何时高于或低于平均销售额。 使用 boolean T/F 将数据中的每个日期标记为高于或低于平均值。
当我在我的数据集上执行此操作时,matplotlib 没有每个日期的条形颜色。
我为这个例子制作了一个玩具套装,当我在玩具套装上运行代码时,它可以正常工作。 我已经包含了实际数据、数据类型和不正确图表的片段。
我的问题是:我应该解决什么问题或查看为什么 matplotlib 没有正确绘制条形图?
实际数据集
实际数据集类型
实际数据集图
请注意,每周应根据数据显示为绿色或红色
实际数据集上的代码
fig = plt.figure()
ax1 = fig.add_subplot()
x = test['FSCL_WK_BGN_DT']
y = test[['total_sls','avg_sales']]
off_season = test['Off_season']
on_season = test['On_season']
ax1.plot(x,y)
ax2 = ax1.twinx()
ax2.bar(x,on_season, color = 'green')
ax2.bar(x,off_season, color = 'red')
玩具示例
dict_sample = {'date': [1,2,3,4,5],
'sales':[100,200,300,100,200],
'avg_sls': 180,
'over':[False,True,True,False,True],
'under':[True,False,False,True,False]
}
df_sample = pd.DataFrame(dict_sample)
df_sample
图形玩具示例代码
ax1 = fig.add_subplot()
x = df_sample['date']
y = df_sample[['sales','avg_sls']]
over = df_sample['over']
under = df_sample['under']
ax1.plot(x,y)
ax2 = ax1.twinx()
ax2.bar(x,over, color = 'green')
ax2.bar(x,under, color = 'red')
代码 Output虽然很难看,但条形图是正确的
根据https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.bar.html ,条的默认宽度为 0.8。 当您使用时间序列 x 轴时,这将变为 0.8 秒,有时可能太小而无法显示任何内容。
尝试
ax2.bar(x,on_season, color = 'green', width=86400*0.8)
ax2.bar(x,off_season, color = 'red', width=86400*0.8)
玩具示例使用不同的 integer 比例尺,这就是它工作得如此出色的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.