Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Color a specific bar in histogram using python

I have a histogram (matplotlib or plotly) and want to color a specific bar, witch has value N in the bar range (for example if N=131 the colored bar must be 130-132). How can i do that?

like image 966
Stas Avatar asked Mar 16 '17 16:03

Stas


1 Answers

When calling plt.hist(), it will return three things. Firstly an array holding the value in each bin. Secondly the values for each of the bins, and lastly an array of patches. These let you modify each bar individually. So all you need to do is determine which bin is for the range 130-132 and then modify the colour, for example:

import numpy as np
import matplotlib.pyplot as plt

values =  np.random.randint(51, 140, 1000)
n, bins, patches = plt.hist(values, bins=np.arange(50, 140, 2), align='left', color='g')
patches[40].set_fc('r')
plt.show()

Would display something like:

example showing one red bar

Here the 41st patch corresponds to the range 130-132 as the bins I have chosen start at 50 and go up to 140 in steps of 2. So there will be 45 bins in total. If you print bins you would see that index 40 is the one you want:

[ 50  52  54  56  58  60  62  64  66  68  70  72  74  76  78  80  82  84
  86  88  90  92  94  96  98 100 102 104 106 108 110 112 114 116 118 120
 122 124 126 128 130 132 134 136 138]
like image 150
Martin Evans Avatar answered Sep 21 '22 01:09

Martin Evans