Plot histogram with colors taken from colormap

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

    I like Bas Swinckels answer, but given that the colormap cm take as parameter a value between 0 and 1, a simpler algorithm would be like this

    import matplotlib.pyplot as plt
    
    Ntotal = 1000
    data = 0.05 * n.random.randn(Ntotal) + 0.5
    
    cm = plt.cm.RdBu_r
    
    n, bins, patches = plt.hist(data, 25, normed=1, color='green')
    for i, p in enumerate(patches):
        plt.setp(p, 'facecolor', cm(i/25)) # notice the i/25
    
    plt.show()
    

提交回复
热议问题