Skip to content
Advertisement

Matplotlib histogram where bins are defined range of FLOATS and colored by it?

I do RMSF analysis and as a results I have list of floats (0.1, 0.3, etc.) and I would like to do a histogram where are bins of defined ranges of the floats. Then I want to have each range of float with corresponding color. I tried to do it with analogies of this script:

from MDAnalysis.analysis.rms import RMSF
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
data = rmsfer.rmsf

N, bins, patches = ax.hist(data, edgecolor='white', linewidth=1)

for i in np.arange(0.3,0.8):
    patches[i].set_facecolor('navy')
for i in np.arange(0.8,1.3):    
    patches[i].set_facecolor('cyan')
for i in np.arange(1.3,1.8):
    patches[i].set_facecolor('yellow')
for i in np.arange(1.8,2.3):
    patches[i].set_facecolor('orange')
for i in np.arange(2.3,3.5):
    patches[i].set_facecolor('red')

I know that there is problem with the float and tried to fix it with numpy and np.arange, but of course it is not so easy for me as I am new to python. Any suggestion, please?

Advertisement

Answer

You would want to pass bins into ax.hist:

fig,ax = plt.subplots()
N, bins, patches = ax.hist(data,bins=[0.3, 0.8,1.3,1.8,2.3,3.5],edgecolor='white')
for (p,c) in zip(patches, ['navy','cyan','yellow','orange','red']):
    p.set_facecolor(c)

Output:

enter image description here

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement