Select the color of the bar in histogram plot based on its value

Question:

I have thousands of data that I want to plot the histogram of them. I want to put the different colors based on the values of the histogram. My values are between 0-10. So, I want to put the color of the bar from red to green. And if it is close to zero, the color should be red and if it is close to 10, the color should be green. Like the image I attached. In the following example, I want to set the color of row h as close to green, and the b is close to red. Here is a simple example, I have multiple bars and values.

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
rating = [8, 4, 5,6]
objects = ('h', 'b', 'c','a')
y_pos = np.arange(len(objects))

plt.barh(y_pos, rating, align='center', alpha=0.5)
plt.yticks(y_pos, objects)


plt.show()

Could you please help me with this? Thank you. enter image description here

Asked By: Sadcow

||

Answers:

To apply colors depending on values, matplotlib uses a colormap combined with a norm. The colormap maps values between 0 and 1 to a color, for example 0 to green, 0.5 to yellow and 1 to red. A norm maps values from a given range to the range 0 to 1, for example, the minimum value to 0 and the maximum value to 1. Applying the colormap to the norm of the given values then gives the desired colors.

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

rating = [8, 4, 5, 6]
objects = ('h', 'b', 'c', 'a')
y_pos = np.arange(len(objects))

cmap = plt.get_cmap('RdYlGn_r')
norm = plt.Normalize(vmin=min(rating), vmax=max(rating))
plt.barh(y_pos, rating, align='center', color=cmap(norm(np.array(rating))))
plt.yticks(y_pos, objects)
plt.show()

colormapping bar colors

Alternatively, the seaborn library could be used for a little bit simpler approach:

import seaborn as sns

rating = [8, 4, 5, 6]
objects = ['h', 'b', 'c', 'a']

ax = sns.barplot(x=rating, y=objects, hue=rating, palette='RdYlGn_r', dodge=False)

seaborn barplot with hue

Answered By: JohanC
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.