How to change the color of a single bar if condition is True

Viewed 50107

Is it possible to change only the color of a single bar in a graph made by matplotlib?

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?

2 Answers

for seaborn you can do something like this:

import seaborn as sns
import numpy as np

values = np.array([2,5,3,6,4,7,1])   
idx = np.array(list('abcdefg')) 
clrs = ['grey' if (x < max(values)) else 'red' for x in values ]
sns.barplot(x=idx, y=values, palette=clrs) # color=clrs)

enter image description here

for matplotlib:

import numpy as np
import matplotlib.pyplot as plt

values = np.array([2,5,3,6,4,7,1])   
idx = np.array(list('abcdefg')) 
clrs = ['grey' if (x < max(values)) else 'red' for x in values ]
plt.bar(idx, values, color=clrs, width=0.4)
plt.show()
Related