Plot histogram with colors taken from colormap

后端 未结 4 2013
無奈伤痛
無奈伤痛 2020-12-08 01:10

I want to plot a simple 1D histogram where the bars should follow the color-coding of a given colormap.

Here\'s an MWE:

import numpy as          


        
4条回答
  •  眼角桃花
    2020-12-08 01:26

    While it isn't what you asked for, if someone else stumbles across this (like I did) looking for the way to do the coloration by height of the bins instead of order, the following code based on Bas's answer would work:

    import numpy as np
    import matplotlib.pyplot as plt
    
    Ntotal = 1000
    data = 0.05 * np.random.randn(Ntotal) + 0.5
    cm = plt.cm.get_cmap('RdYlBu_r')
    
    n, bins, patches = plt.hist(data, 25, normed=1, color='green')
    # To normalize your values
    col = (n-n.min())/(n.max()-n.min())
    for c, p in zip(col, patches):
        plt.setp(p, 'facecolor', cm(c))
    plt.show()
    

提交回复
热议问题