【问题标题】:How to plot a histogram with unequal widths without computing it from raw data?如何在不从原始数据计算的情况下绘制宽度不等的直方图?
【发布时间】:2013-07-02 15:31:32
【问题描述】:

Matplotlib 的 hist 说“计算并绘制 x 的直方图”。我想制作一个情节 先不计算任何东西。我有 bin 宽度(不相等)和每个 bin 中的总量,我想绘制一个频率-数量直方图。

以数据为例

cm      Frequency
65-75   2
75-80   7
80-90   21
90-105  15
105-110 12

它应该制作这样的情节:

http://www.gcsemathstutor.com/histograms.php

其中块的面积代表每个类别中的频率。

【问题讨论】:

    标签: matplotlib histogram


    【解决方案1】:

    与 David Zwicker 一样工作:

    import numpy as np
    import matplotlib.pyplot as plt
    
    freqs = np.array([2, 7, 21, 15, 12])
    bins = np.array([65, 75, 80, 90, 105, 110])
    widths = bins[1:] - bins[:-1]
    heights = freqs.astype(np.float)/widths
        
    plt.fill_between(bins.repeat(2)[1:-1], heights.repeat(2), facecolor='steelblue')
    plt.show()
    

    【讨论】:

      【解决方案2】:

      你想要一个bar chart

      import numpy as np
      import matplotlib.pyplot as plt
      
      x = np.sort(np.random.rand(6))
      y = np.random.rand(5)
      
      plt.bar(x[:-1], y, width=x[1:] - x[:-1], align='edge')
      
      plt.show()
      

      这里x 包含条的边缘,y 包含高度(不是区域!)。请注意,x 中的元素比 y 中的元素多一个,因为边比条形多一个。

      用原始数据和面积计算:

      from __future__ import division
      import numpy as np
      import matplotlib.pyplot as plt
      
      frequencies = np.array([2, 7, 21, 15, 12])
      bins = np.array([65, 75, 80, 90, 105, 110])
      
      widths = bins[1:] - bins[:-1]
      heights = frequencies/widths
      
      plt.bar(bins[:-1], heights, width=widths, align='edge')
      
      plt.show()
      

      【讨论】:

      • 有没有办法达到和histtype='stepfilled'一样的效果?
      • 这些示例不再适用。栏的默认位置已更改?
      猜你喜欢
      • 2017-12-04
      • 2012-07-13
      • 2017-11-22
      • 2021-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-04
      相关资源
      最近更新 更多