Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 942
anonuser0428 Avatar asked Sep 19 '13 19:09

anonuser0428


2 Answers

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

like image 181
tacaswell Avatar answered Oct 02 '22 17:10

tacaswell


import pandas as pd
import matplotlib.pyplot as plt  

df = pd.DataFrame([1,2,3,4], [1,2,3,4])   
color = ['red','blue','green','orange']
df.plot(kind='bar', y=0, color=color, legend=False, rot=0)

enter image description here

like image 44
Bisi Afolalu Avatar answered Oct 02 '22 17:10

Bisi Afolalu