【问题标题】:matplotlib histogram with frequency and counts带有频率和计数的 matplotlib 直方图
【发布时间】:2015-04-26 21:19:44
【问题描述】:

我有数据(来自一个有两列的空格分隔文本文件),它已经分箱但宽度仅为 1。我想将此宽度增加到大约 5。如何在 Python 中使用 numpy/matplotlib 执行此操作?

使用,

data = loadtxt('file.txt')
x = data[:, 0]
y = data[:, 1]
plt.bar(x,y)

创建过多的条形图并使用,

plt.hist(data)

没有适当地绘制直方图。我想我不明白 matplotlib 的直方图是如何工作的。

查看下面的一些数据。

264 1
265 1
266 4
267 2
268 2
269 2
270 2
271 2
272 5
273 3
274 2
275 6
276 7
277 3
278 7
279 5
280 9
281 4
282 8
283 11
284 9
285 15
286 19
287 11
288 12
289 10
290 13
291 18
292 20
293 14
294 15

【问题讨论】:

    标签: python numpy matplotlib


    【解决方案1】:

    如果在使用plt.bar 之前使用numpy.reshape 转换数据会怎样,例如:

    In [83]: import numpy as np
    
    In [84]: import matplotlib.pyplot as plt
    
    In [85]: data = np.array([[1,2,3,4,5,6], [4,3,8,9,1,2]]).T
    
    In [86]: data
    Out[86]: 
    array([[1, 4],
           [2, 3],
           [3, 8],
           [4, 9],
           [5, 1],
           [6, 2]])
    
    In [87]: y = data[:,1].reshape(-1,2).sum(axis=1)
    
    In [89]: y
    Out[89]: array([ 7, 17,  3])
    
    
    In [91]: x = data[:,0].reshape(-1,2).mean(axis=1)
    
    In [92]: x
    Out[92]: array([ 1.5,  3.5,  5.5])
    
    In [96]: plt.bar(x, y)
    Out[96]: <Container object of 3 artists>
    
    In [97]: plt.show()
    

    【讨论】:

    • 请不要使用pylab 使用import matplotlib.pyplot as plt 进行绘图,使用import numpy as np 进行数学运算。
    • @tcaswell,为什么? pylab 有什么问题?我得到了相同的结果。
    • 因为它批量导入各种东西。如果周围没有太多示例,我们会弃用它。
    • 这也极大地混淆了哪里函数的来源。 MPL 获得了非零数量的错误报告,这些错误报告确实应该是 numpy 的。
    • 谢谢! :) 使互联网成为一个更准确的地方
    【解决方案2】:

    我不是 matplotlib 专家,但我发现 hist 非常有用。 matplotlib site 上的示例很好地概述了一些功能。

    我不知道如何在不转换的情况下使用您提供的示例数据。在创建直方图之前,我更改了您的示例以对这些数据进行去量化。

    我使用 this question's first answer 计算了 bin 大小。

    import matplotlib.pyplot as plt
    import numpy as np
    
    data = np.loadtxt('file.txt')
    dequantized = data[:,0].repeat(data[:,1].astype(int))
    
    dequantized[0:7]
    # Each row's first column is repeated the number of times found in the
    # second column creating a single array.
    # array([ 264.,  265.,  266.,  266.,  266.,  266.,  267.])
    
    def bins(xmin, xmax, binwidth, padding):
        # Returns an array of integers which can be used to represent bins
        return np.arange(
            xmin - (xmin % binwidth) - padding,
            xmax + binwidth + padding,
            binwidth)
    
    histbins = bins(min(dequantized), max(dequantized), 5, 5)
    plt.figure(1)
    plt.hist(dequantized, histbins)
    plt.show()
    

    显示的直方图如下所示。

    我希望这个例子有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-14
      • 1970-01-01
      • 2015-06-11
      • 2013-10-09
      • 2020-08-08
      • 2016-01-15
      • 2012-04-03
      相关资源
      最近更新 更多