【问题标题】:How to draw a histogram of bins of the same width and different height in a certain interval?如何在一定区间内绘制相同宽度不同高度的bin的直方图?
【发布时间】:2020-06-26 15:07:30
【问题描述】:

我有一个区间0.0..1.0,里面有10个箱子的高度,例如:

[0.1, 0.2, 0.3, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]

如何使用 Matplotlib 以相同宽度渲染这些 bin 的直方图?

【问题讨论】:

  • 在你的例子中,所有的箱子都应该有 same 高度吗?如果是这样,这不是一个很好的例子。
  • @DYZ,关键问题是 Matplotlib 的 pyplot.hist 函数本身对输入值进行分组,但是我的输入数据已经分组并且 bin 的高度是已知的。

标签: python matplotlib math histogram bins


【解决方案1】:

在hist的doc字符串中有明确说明

Docstring:
Plot a histogram.

Compute and draw the histogram of *x*.  The return value is a tuple
(*n*, *bins*, *patches*) or ([*n0*, *n1*, ...], *bins*, [*patches0*,
*patches1*, ...]) if the input contains multiple data.  See the
documentation of the *weights* parameter to draw a histogram of
already-binned data.
In [24]: import numpy as np
    ...: import matplotlib.pyplot as plt
    ...: 
    ...: w = [0.1, 0.2, 0.3, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]
    ...: n = len(w)
    ...: 
    ...: left, right = 0.0, 1.0
    ...: plt.hist(np.arange(left+d/2, right, d),
    ...:          np.arange(left, right+d/2, d),
    ...:          weights=w, rwidth=0.7)
    ...: plt.show()

【讨论】:

    【解决方案2】:

    plt.stairs / ax.stairs

    从 matplotlib 3.4 开始,预分箱数据可以绘制为 stairs。 matplotlib 库包含how to plot stairs 的示例。


    stairs 需要值和边。我们已经有了w 中的值,所以我们只需要从left 和right 边界生成边:

    left, right = 0, 1
    bins = np.linspace(left, right, len(w))
    edges = np.append(bins, right)
    
    plt.stairs(w, edges, fill=True)
    

    注意右边缘是重复的(这也意味着与值相比有一个额外的边缘):

    >>> edges
    # [0.0, 0.11, 0.22, 0.33, 0.44, 0.56, 0.67, 0.78, 0.89, 1.0, 1.0]
    

    这是因为edges 是沿滑动窗口成对拍摄的:

      w          edges
    0.1   ( 0.0, 0.11)
    0.2   (0.11, 0.22)
    0.3   (0.22, 0.33)
    ...            ...
    0.1   (0.89,  1.0)
    0.1   ( 1.0,  1.0)
    

    【讨论】:

      【解决方案3】:

      除了hist 函数,您还可以使用bar 函数。

      import matplotlib.pyplot as plt
      
      xs = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]
      heights = [0.1, 0.2, 0.3, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]
      bar_width = 0.08
      
      plt.bar(xs, heights, bar_width)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多