【问题标题】:matplotlib density graph / histogrammatplotlib 密度图/直方图
【发布时间】:2019-07-07 15:36:33
【问题描述】:

我有一个数组:[0,0,0,0,0,1,1,1,1,1,0,0,0,1,1,1](16 长) 如何创建密度直方图,例如 bins=4 以查看 1:s 最多的位置?例如,该直方图在中间部分会非常高,并且在结尾处略微升高(开头和结尾处大多数为 1:s)。 我有这个:

plt.hist([0,0,0,0,0,1,1,1,1,1,0,0,0,1,1,1], bins=4)

This is what i get。这个直方图只是表示它的 1:s 和 0:s 一样多。

我以后如何创建一个图表(线)来显示直方图的平均上升和下降?

【问题讨论】:

    标签: python arrays matplotlib graph histogram


    【解决方案1】:

    我不会称其为直方图。它更像是一个空间密度图。 所以你可以枚举你的列表,使得第一个元素的数字为 0,最后一个元素的数字为 15。然后将此列表分为 4 个箱。在每个垃圾箱中,您可以计算看到1 的频率。要自动执行此操作,可以选择scipy.stats.binned_statistic

    import matplotlib.pyplot as plt
    import numpy as np
    from scipy.stats import binned_statistic
    
    data = [0,0,0,0,0,1,1,1,1,1,0,0,0,1,1,1]
    x = np.arange(len(data))
    
    s, edges, _ = binned_statistic(x, data, bins=4, statistic = lambda c: len(c[c==1]))
    print(s, edges)
    plt.bar(edges[:-1], s, width=np.diff(edges), align="edge", ec="k")
    plt.show()
    

    所以这里的边是[0., 3.75, 7.5, 11.25, 15.],每个bin中1的数量是[0. 3. 2. 3.]

    【讨论】:

      【解决方案2】:

      直方图不会评估您的值的位置;它是数据分布的表示,值在 hist 中的位置无关紧要; min 和 max 表示数据的最小值和最大值。 我会尝试设置一个索引并将其用作您的范围。

      我认为这是与您描述的图表最接近的答案: Pandas bar plot with binned range 此处重要的BeingEnrnest 的回答也可能会有所帮助。

      Plot a histogram using the index as x-axis labels

      【讨论】:

        猜你喜欢
        • 2020-03-09
        • 1970-01-01
        • 2017-07-17
        • 2017-05-19
        • 2011-07-16
        • 2016-12-30
        • 1970-01-01
        • 2019-08-12
        • 2014-12-07
        相关资源
        最近更新 更多