【发布时间】:2022-01-27 23:04:15
【问题描述】:
我正在处理时间序列数据集。我想要一个销售折线图和一条显示该时间段内平均销售额的水平线。这部分工作正常。
我想在折线图顶部添加条形图,显示销售额何时高于或低于平均销售额。数据中的每个日期都用布尔 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')
代码输出 尽管丑陋,但条形图是正确的
【问题讨论】:
标签: python pandas matplotlib