【问题标题】:how to change the color of a single bar if condition is True matplotlib如果条件为真 matplotlib 如何更改单个条的颜色
【发布时间】:2011-04-19 11:15:34
【问题描述】:

我一直在用谷歌搜索是否可以只更改由 matplotlib 制作的图表中条形的颜色。 想象一下这张图:

假设我已经评估了 1 到 10 个,并且当用户选择评估时,我会为每个评估生成一个图表。对于每次评估,其中一个男孩将获胜。
所以对于每个图表,我想用不同的颜色留下获胜者栏,假设 Jim 赢得了评估 1。吉姆条是红色的,其他的是蓝色的。

我有一本包含值的字典,我试图做的是这样的:

for value in dictionary.keys(): # keys are the names of the boys
    if winner == value:
        facecolor = 'red'
    else:
        facecolor = 'blue'

ax.bar(ind, num, width, facecolor=facecolor)

有人知道这样做的方法吗?

提前致谢:)

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    对于 seaborn,你可以这样做:

    values = np.array([2,5,3,6,4,7,1])   
    idx = np.array(list('abcdefg')) 
    clrs = ['grey' if (x < max(values)) else 'red' for x in values ]
    sb.barplot(x=idx, y=values, palette=clrs) # color=clrs)
    

    对于 matplotlib:

    values = np.array([2,5,3,6,4,7,1])   
    idx = np.array(list('abcdefg')) 
    clrs = ['grey' if (x < max(values)) else 'red' for x in values ]
    plt.bar(idx, values, color=clrs, width=0.4)
    plt.show()
    

    【讨论】:

    • Paddy 的解决方案也适用于 Matplotlib:plt.bar(idx, values, color=clrs)
    【解决方案2】:

    您需要使用color 而不是facecolor。您还可以将颜色指定为列表而不是标量值。所以对于你的例子,你可以有color=['r','b','b','b','b']

    例如,

    import numpy as np
    import matplotlib.pyplot as plt
    
    fig = plt.figure()
    ax = fig.add_subplot(111)
    
    N = 5
    ind = np.arange(N)
    width = 0.5
    vals = [1,2,3,4,5]
    colors = ['r','b','b','b','b']
    ax.barh(ind, vals, width, color=colors)
    
    plt.show()
    

    是一个完整的例子,告诉你你想要什么。

    回答您的评论:

    colors = []
    for value in dictionary.keys(): # keys are the names of the boys
        if winner == value:
            colors.append('r')
        else:
            colors.append('b')
    
    bar(ind,num,width,color=colors)
    

    【讨论】:

    • 实际上是你在条形图中使用 facecolor 它也可以。但无论如何我尝试改变颜色,这不是问题
    • 啊,好吧,我以前从未使用过 facecolor,我的错。但是你可以使用颜色作为列表,我不确定 facecolor 是否同样工作。
    • 这将是一个很好的解决方案,但问题是红色条可能会改变。在示例中,我使用了男孩,因此获胜者可能是 John,而其他时候则是 Will。我会自动绘制图表,因此如果您选择评估 1,例如获胜者是彼得,但在评估 8 中,获胜者可能是西蒙。
    • 当您通过值循环进行评估以生成颜色数组时。我在回答中举了一个例子。
    • 如果我想调用 plot 而不是 bar 怎么办?
    猜你喜欢
    • 2014-03-24
    • 2020-10-27
    • 2020-04-12
    • 1970-01-01
    • 1970-01-01
    • 2013-02-20
    • 2021-01-07
    • 1970-01-01
    相关资源
    最近更新 更多