【问题标题】:Change the edgecolor of single bar in bar plot through time随时间改变条形图中单个条形的边缘颜色
【发布时间】:2020-10-29 03:37:08
【问题描述】:

我有一个如下所示的数据框:

df_

Daily Risk Score    Green   Orange  Red
Date            
2020-07-08  505 150 22
2020-07-09  624 36  17
2020-07-10  611 41  25
2020-07-11  625 30  22
2020-07-12  635 25  17
2020-07-13  595 51  31
2020-07-14  509 121 47
2020-07-15  501 143 33
2020-07-16  489 164 24
2020-07-17  465 187 25
2020-07-18  482 167 28
2020-07-19  503 143 31
2020-07-20  500 148 29
2020-07-21  491 158 28
date_list=pd.date_range(today, (today+dt.timedelta(days=13)), freq='D').strftime('%d %b')

然后我使用 matplotlib 创建一个堆积条形图:

fig, ax = plt.subplots(figsize=(16,12))
plot_day=dt.date.today().strftime('%d %b')
plt.bar(date_list, df_['Green'], color='green', zorder=10)
plt.bar(date_list, df_['Orange'], color='orange', bottom=df_['Green'], zorder=10)
plt.bar(date_list, df_['Red'], color='red', bottom=bars_new, zorder=10)
plt.grid(axis='y', zorder=0)
plt.axvline(x=plot_day, c='k', linestyle='--', zorder=11)

目前,为了表示当天,我使用垂直虚线。但是,我想尝试更改边缘颜色,看看是否会产生更多印象。如何更改当前日期(7 月 8 日)整个条形的边缘颜色?

【问题讨论】:

    标签: python pandas dataframe datetime matplotlib


    【解决方案1】:

    让我们尝试传递edgecolor 并同时使用df.plot.bar

    today = pd.to_datetime('2020-07-08')
    edge_colors = np.where(df.index==today, 'r', 'w')
    
    df.plot.bar(stacked=True, width=0.8, edgecolor=edge_colors)
    

    输出:

    【讨论】:

    • 有没有办法使用 matplotlib 绘图来做到这一点,而不是 pandas?我已经编写了要在 matplotlib 中使用的代码,如果有一个考虑到这一点的解决方案会很好。
    • @EliTurasky 只需将相同的 edgecolor = edge_colors 传递给代码中的每个 plt.bar 命令。也就是说,我不确定您为什么不选择plot.bar() 解决方案。它更简洁。
    猜你喜欢
    • 2020-11-03
    • 1970-01-01
    • 1970-01-01
    • 2011-08-03
    • 2012-01-19
    • 1970-01-01
    • 1970-01-01
    • 2016-07-26
    • 1970-01-01
    相关资源
    最近更新 更多