Any way to create histogram with matplotlib.pyplot without plotting the histogram?

前端 未结 4 2135

I am using matplotlib.pyplot to create histograms. I\'m not actually interested in the plots of these histograms, but interested in the frequencies and bins (I know I can write

4条回答
  •  被撕碎了的回忆
    2021-02-20 06:22

    I don't know if I'm understanding your question very well, but here, you have an example of a very simple home-made histogram (in 1D or 2D), each one inside a function, and properly called:

    import numpy as np
    import matplotlib.pyplot as plt
    
    def func2d(x, y, nbins):
        histo, xedges, yedges = np.histogram2d(x,y,nbins)
        plt.plot(x,y,'wo',alpha=0.3)
        plt.imshow(histo.T, 
                   extent=[xedges.min(),xedges.max(),yedges.min(),yedges.max()],
                   origin='lower', 
                   interpolation='nearest', 
                   cmap=plt.cm.hot)
        plt.show()
    
    def func1d(x, nbins):
        histo, bin_edges = np.histogram(x,nbins)
        bin_center = 0.5*(bin_edges[1:] + bin_edges[:-1])
        plt.step(bin_center,histo,where='mid')
        plt.show()
    
    x = np.random.normal(1.5,1.0, (1000,1000))
    
    func1d(x[0],40)
    func2d(x[0],x[1],40)
    

    Of course, you may check if the centering of the data is right, but I think that the example shows some useful things about this topic.

    My recommendation: Try to avoid any loop in your code! They kill the performance. If you look, In my example there aren't loops. The best practice in numerical problems with python is avoiding loops! Numpy has a lot of C-implemented functions that do all the hard looping work.

提交回复
热议问题