如果条件为True,如何更改单个条形的颜色matplotlib [英] how to change the color of a single bar if condition is True matplotlib

查看:120
本文介绍了如果条件为True,如何更改单个条形的颜色matplotlib的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

假设我已经评估了1到10,并且每当用户选择评估时,我都会生成一个图表.对于每个评估,其中一个男孩将获胜.
因此,对于每个图形,我想用不同的颜色保留获胜者栏,例如,吉姆赢得了评估1.吉姆·巴(Jim bar)将是红色,其他的将是蓝色.

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

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)

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

先谢谢您了:)

解决方案

您需要使用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)

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:

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.

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 :)

解决方案

You need to use color instead 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']

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)

这篇关于如果条件为True,如何更改单个条形的颜色matplotlib的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆