Python 如果条件为真,如何更改单个条的颜色 matplotlib
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3832809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to change the color of a single bar if condition is True matplotlib
提问by psoares
I've been googleing to find if it's possible to change only the color of a bar in a graph made by matplotlib. Imagine this graph:
我一直在用谷歌搜索是否可以只更改由 matplotlib 制作的图表中条形的颜色。想象一下这个图:


let's say I've evaluation 1 to 10 and for each one I've a graph generate when the user choice the evaluation. For each evaluation one of this boys will win.
So for each graph, I would like to leave the winner bar in a different color, let's say Jim won evaluation1. Jim bar would be red, and the others blue.
假设我进行了 1 到 10 次评估,并且对于每个评估,当用户选择评估时,我都会生成一个图表。对于每个评估,这个男孩中的一个将获胜。
因此,对于每个图表,我想以不同的颜色保留获胜者栏,假设吉姆赢得了评估 1。吉姆酒吧会是红色的,而其他人是蓝色的。
I have a dictionary with the values, what I tried to do was something like this:
我有一本带有值的字典,我试图做的是这样的:
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)
Anyone knows a way of doing this?
有人知道这样做的方法吗?
Thanks in advance :)
提前致谢 :)
采纳答案by GWW
You need to use colorinstead of facecolor. You can also specify color as a list instead of a scalar value. So for your example, you could have color=['r','b','b','b','b']
您需要使用color而不是facecolor. 您还可以将颜色指定为列表而不是标量值。所以对于你的例子,你可以有color=['r','b','b','b','b']
For example,
例如,
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()
is a full example showing you what you want.
是一个完整的示例,显示您想要什么。
To answer your comment:
要回答您的评论:
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)

