Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

python - how to change the color of a single bar if condition is True matplotlib

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:

alt text

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...