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
217 views
in Technique[技术] by (71.8m points)

python - vary the color of each bar in bargraph using particular value

I have a bar-graph like the following: http://matplotlib.org/examples/api/barchart_demo.html

In that case, let's assume each of the groups G1- G5 represent the average score that men in each group got on some exam and women in each group got on the same exam.

Now let's say I have some other feature associated with each group (avg. likability (float between 1-5)).

Ex: Avg Likability of men in G1 - 1.33
                   Avg Likability of women in G1 - 4.6
                   Avg Likability of men in G2- 5.0
                   .... etc...

Lets assume 1 - not likable and 5 - very likable

I want to know how I can incorporate this feature of likability into each bar by changing the shade of the color example: since men of group 1 in the above example have 1.33, their graph would be shaded a lighter shade of red than the men of G2, since men of G2 have 5.0 likability, their bar would be the darkest shade of red in the graph, and the same thing for the women.

I hope I have made myself clear. I would really appreciate if someone could point me to a resource in matplotlib that could achieve this, as I am very new to this package.

Thanks in advance.

Question&Answers:os

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

1 Reply

0 votes
by (71.8m points)

bar takes a list of colors as an argument (docs). Simply pass in the colors you want.

import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.colors import Normalize
from numpy.random import rand

fig, ax = plt.subplots(1, 1)
# get a color map
my_cmap = cm.get_cmap('jet')
# get normalize function (takes data in range [vmin, vmax] -> [0, 1])
my_norm = Normalize(vmin=0, vmax=5)
# some boring fake data
my_data = 5*rand(5)
ax.bar(range(5), rand(5), color=my_cmap(my_norm(my_data)))

plt.show()

enter image description here


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

...