【问题标题】:Vertical Histogram in Python and MatplotlibPython 和 Matplotlib 中的垂直直方图
【发布时间】:2014-04-15 12:40:05
【问题描述】:

如何制作垂直直方图。有什么选择吗,还是应该从头开始构建?我想要的是上图看起来像下面的图,但在垂直轴上!

from matplotlib import pyplot as plt
import numpy as np
sample=np.random.normal(size=10000)
vert_hist=np.histogram(sample,bins=30)
ax1=plt.subplot(2,1,1)
ax1.plot(vert_hist[0],vert_hist[1][:-1],'*g')

ax2=plt.subplot(2,1,2)
ax2.hist(sample,bins=30)
plt.show()

【问题讨论】:

    标签: python numpy matplotlib plot histogram


    【解决方案1】:

    我使用 ax[1] 作为子图

    f ,ax = plt.subplots(1,2,figsize = (30, 13),gridspec_kw={'width_ratios': [5, 1]})

    以下代码将直方图顺时针旋转 90 度。它还为垃圾箱绘制了一条拟合曲线 关键参数是orientation=u'horizo​​ntal'

    ax[1].hist(data,normed =1, bins = num_bin, color = 'yellow' ,alpha = 1, orientation=u'horizontal') 
    
    # Fit a normal distribution to the data:
    mu, std = norm.fit(data)
    
    # Plot the PDF.
    xmin = min(data)
    xmax = max(data)
    
    x = np.linspace(xmin, xmax, 10000)
    p = norm.pdf(x, mu, std)
    
    base = plt.gca().transData
    rot = transforms.Affine2D().rotate_deg(-90)  # rotate the histogram line 90 degress clockwise
    
    ax[1].plot(-x, p,  'r',linewidth=2, transform = rot+base)  # use -x for the reverse y-axis plotting
    

    【讨论】:

      【解决方案2】:

      ax.hist 中使用orientation="horizontal"

      from matplotlib import pyplot as plt
      import numpy as np
      
      sample = np.random.normal(size=10000)
      
      vert_hist = np.histogram(sample, bins=30)
      ax1 = plt.subplot(2, 1, 1)
      ax1.plot(vert_hist[0], vert_hist[1][:-1], '*g')
      
      ax2 = plt.subplot(2, 1, 2)
      ax2.hist(sample, bins=30, orientation="horizontal");
      plt.show()
      

      【讨论】:

        【解决方案3】:

        只需将barh() 用于情节:

        import math
        from matplotlib import pyplot as plt
        import numpy as np
        sample=np.random.normal(size=10000)
        vert_hist=np.histogram(sample,bins=30)
        
        # Compute height of plot.
        height = math.ceil(max(vert_hist[1])) - math.floor(min(vert_hist[1]))
        
        # Compute height of each horizontal bar.
        height = height/len(vert_hist[0])
        
        ax1=plt.subplot(2,1,1)
        ax1.barh(vert_hist[1][:-1],vert_hist[0], height=height)
        
        ax2=plt.subplot(2,1,2)
        ax2.hist(sample,bins=30)
        plt.show()
        

        【讨论】:

          最近更新 更多