jay
jay

Reputation: 1463

Ordering colors in Barplot Using Sequential feature Matplotlib

I am working on getting a barplot using MatPlotlib. Here is the data frame I am working with;

df= pd.DataFrame({'col0':['Chicago', 'Baltimore','New Orleans','Philadelphia'],\
      'col1':[400, 610, 800, 100]})

Then I tried to make a barplot using following code;

fig = plt.figure(figsize=(12,6))
ax = fig.add_subplot(111)


city_name = df['col0']
x_pos = np.arange(len(city_name))
count = df['col1']

my_cmap = cm.get_cmap('Reds')
ax.bar(x_pos, count, align='center', color=my_cmap(count))
ax.set_xticks(x_pos)
ax.set_xticklabels(city_name)
ax.set_ylabel('Gun Incident Count Per 100000')
ax.set_title('Gun Incident Count In Cities Across US Between 2013 And 2017')
ax.tick_params(axis='x', rotation=90)

plt.show()

Using above code, I get the following plot;

enter image description here

As you can see, all the bars of same color. But my goal is to get the bars of different colors, with color intensity changing from lighter to dark as the value increases for col1.

Thanks in advance for the help.

Upvotes: 0

Views: 139

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150825

Let's try the idea from the question/answer linked by Ben:

import matplotlib.cm as cm

# get a linear color map
cmap=cm.get_cmap('Blues')

# we use these to scale data to 0-1
min_val,max_val = df['col1'].agg(['min','max'])

fig,ax = plt.subplots()
for i,r in df.iterrows():
    scale = (r['col1'] - min_val)/(max_val-min_val)
    ax.bar(r['col0'], r['col1'], color=cmap(scale), edgecolor='k')

Output:

enter image description here

And if you need the color bar, here is an example of how to do so.

Upvotes: 1

Related Questions