Plot histogram with colors taken from colormap

后端 未结 4 2025
無奈伤痛
無奈伤痛 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:23

    The hist command returns a list of patches, so you can iterate over them and set their color like so:

    import numpy as n
    import matplotlib.pyplot as plt
    
    # Random gaussian data.
    Ntotal = 1000
    data = 0.05 * n.random.randn(Ntotal) + 0.5
    
    # This is  the colormap I'd like to use.
    cm = plt.cm.get_cmap('RdYlBu_r')
    
    # Plot histogram.
    n, bins, patches = plt.hist(data, 25, normed=1, color='green')
    bin_centers = 0.5 * (bins[:-1] + bins[1:])
    
    # scale values to interval [0,1]
    col = bin_centers - min(bin_centers)
    col /= max(col)
    
    for c, p in zip(col, patches):
        plt.setp(p, 'facecolor', cm(c))
    
    plt.show()
    

    To get the colors, you need to call the colormap with a value between 0 and 1. Resulting figure:

    enter image description here

提交回复
热议问题