【问题标题】:How to conditionally assign colors to a stacked bar plot?如何有条件地为堆积条形图分配颜色?
【发布时间】:2020-05-17 16:27:59
【问题描述】:

我有以下数据框:

      key1 key2 key3 ...
time
Jan   0.5  0.4  0.2  ...
Feb   0.3  0.4  0.4  ...
Mar   0.2  0.4  0.1  ...
Apr   0.5  0.3  0.8  ...
...   ...  ...  ...

我创建了如下条形图:

import matplotlib.pyplot as plt
ax = df10.plot(kind='bar', figsize=(15, 10), fontsize=12, stacked='true')
plt.show()

这给了我一个包含许多条形和许多颜色的堆叠条形图,乍一看并不能很好地概述。 因此,我只想突出显示那些产生影响 (>0.5) 的条并隐藏不重要的条(通过将它们涂成灰色)。

因此,目标是一些有条件的着色:值低于 0.5 的条形应该用灰色着色,其余的应该接受预定义的颜色。

我尝试了很多方法,但找不到有效的解决方案。我对 python/matplotlib 很陌生。 任何人都可以帮助我吗?非常感谢您,非常感谢您的帮助!

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    您可以遍历斧头的所有补丁,检查它们是否为Rectangle,并根据某些条件更改颜色。

    除了更改颜色外,其他选项包括更改阴影样式 (rect.set_hatch('x')) 或透明度 (rect.set_alpha(0.4))。

    下面是一些示例代码:

    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    from matplotlib.patches import Rectangle
    
    df10 = pd.DataFrame({f'key{i}': np.random.randint(2, 9, 12) * 0.1 for i in range(1, 7)},
                        index=['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'])
    
    ax = df10.plot(kind='bar', figsize=(15, 10), fontsize=12, stacked=True, rot=0, color=plt.cm.Dark2.colors)
    
    for rect in ax.get_children():
        if type(rect) == Rectangle:
            if rect.get_height() < 0.5:
                rect.set_facecolor('lavender')
    ax.tick_params(axis='x', length=0) # optionally remove the tick marks on the x-axis
    plt.show()
    

    【讨论】:

    • 这能回答你的问题吗?
    猜你喜欢
    • 2017-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-03
    • 2020-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多