Python: Creating a 2D histogram from a numpy matrix

后端 未结 4 1815
清歌不尽
清歌不尽 2020-12-25 15:31

I\'m new to python.

I have a numpy matrix, of dimensions 42x42, with values in the range 0-996. I want to create a 2D histogram using this data. I\'ve been looking a

4条回答
  •  北海茫月
    2020-12-25 15:38

    If you have not only the 2D histogram matrix but also the underlying (x, y) data, then you could make a scatter plot of the (x, y) points and color each point according to its binned count value in the 2D-histogram matrix:

    import numpy as np
    import matplotlib.pyplot as plt
    
    n = 10000
    x = np.random.standard_normal(n)
    y = 2.0 + 3.0 * x + 4.0 * np.random.standard_normal(n)
    xedges, yedges = np.linspace(-4, 4, 42), np.linspace(-25, 25, 42)
    hist, xedges, yedges = np.histogram2d(x, y, (xedges, yedges))
    xidx = np.clip(np.digitize(x, xedges), 0, hist.shape[0]-1)
    yidx = np.clip(np.digitize(y, yedges), 0, hist.shape[1]-1)
    c = hist[xidx, yidx]
    plt.scatter(x, y, c=c)
    
    plt.show()
    

    Example scatter plot of 2D histogram

提交回复
热议问题