【问题标题】:Matplotlib not plotting all data points in bar graphMatplotlib 未在条形图中绘制所有数据点
【发布时间】: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


    【解决方案1】:

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

    玩具示例使用不同的整数刻度,这就是它工作得如此出色的原因。

    【讨论】:

    • 嗨!这很好用!我试着做 86400*.8 但它使条太大了。我将每个调整为 2.5,然后所有条都正确显示。感谢您的建议和解释。他们非常有帮助:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-28
    • 1970-01-01
    • 2017-06-30
    • 1970-01-01
    • 1970-01-01
    • 2018-11-30
    • 1970-01-01
    相关资源
    最近更新 更多