【问题标题】:python plot simple histogram given binned data给定分箱数据的python绘制简单直方图
【发布时间】:2012-08-31 11:24:23
【问题描述】:

我有计数数据(其中 100 个),每个数据对应一个 bin(0 到 99)。我需要将这些数据绘制为直方图。但是,直方图计算了这些数据并且无法正确绘制,因为我的数据已经被分箱了。

import random
import matplotlib.pyplot as plt
x = random.sample(range(1000), 100)
xbins = [0, len(x)]
#plt.hist(x, bins=xbins, color = 'blue') 
#Does not make the histogram correct. It counts the occurances of the individual counts. 

plt.plot(x)
#plot works but I need this in histogram format
plt.show()

【问题讨论】:

  • 您可以使用answeranswer 中的代码作为示例,将已分箱的数据绘制为直方图。

标签: python plot matplotlib histogram


【解决方案1】:

您也可以使用 matplotlib 的 hist 来实现这一点,不需要 numpy.您基本上已经将垃圾箱创建为xbins。在这种情况下,x 将是您的权重。

plt.hist(xbins,weights=x)

【讨论】:

    【解决方案2】:

    如果我理解您想要正确实现的目标,那么以下内容应该可以满足您的需求:

    import matplotlib.pyplot as plt
    plt.bar(range(0,100), x)
    plt.show()
    

    它没有使用hist(),但看起来您已经将数据放入 bin,所以没有必要。

    【讨论】:

    • 如果您希望bar 看起来更像hist 输出,请使用此answer 或此answer 中的代码作为通过bar 绘图绘制直方图的示例。
    【解决方案3】:

    太棒了,谢谢!这就是我认为 OP 想要做的事情:

    import random
    import matplotlib.pyplot as plt
    x=[x/1000 for x in random.sample(range(100000),100)]
    xbins=range(0,len(x))
    plt.hist(x, bins=xbins, color='blue')
    plt.show()
    

    【讨论】:

      【解决方案4】:

      我很确定您的问题是垃圾箱。它不是限制列表,而是 bin 边缘列表。

      xbins = [0,len(x)]
      

      在您的情况下返回一个包含[0, 100] 的列表,表明您想要一个位于 0 的 bin 边缘和一个位于 100 的 bin。所以您得到一个从 0 到 100 的 bin。 你想要的是:

      xbins = [x for x in range(len(x))]
      

      返回:

      [0,1,2,3, ... 99]
      

      这表示您想要的 bin 边缘。

      【讨论】:

        【解决方案5】:

        问题出在您的 xbin 上。你目前有

        xbins = [0, len(x)]
        

        这将为您提供列表 [0, 100]。这意味着您只会看到 1 个 bin(不是 2 个)以 0 为界,以 100 为界。我不完全确定您想要从直方图中得到什么。如果你想有 2 个不均匀间隔的 bin,你可以使用

        xbins = [0, 100, 1000]
        

        在一个 bin 中显示低于 100 的所有内容,在另一个 bin 中显示其他所有内容。另一种选择是使用整数值来获得一定数量的均匀间隔的 bin。也就是说

        plt.hist(x, bins=50, color='blue')
        

        其中 bins 是所需的 bin 数量。

        在旁注中,每当我不记得如何使用 matplotlib 做某事时,我通常会去thumbnail gallery 并找到一个看起来或多或少我想要完成的示例。这些示例都有随附的源代码,因此非常有用。 matplotlib 的documentation 也可以很方便。

        【讨论】:

          【解决方案6】:

          查看 matplotlib 文档中的直方图 examples。您应该使用hist 函数。如果默认情况下它不会产生您期望的结果,那么在将其提供给hist 之前使用hist 的参数并准备/转换/修改您的数据。我不太清楚你想要达到什么目标,所以我现在无法提供帮助。

          【讨论】:

          • 尝试了一段时间后,我问了这个问题。我唯一担心的是,如果我能用 hist 函数实现上述代码的功能。
          猜你喜欢
          • 1970-01-01
          • 2021-10-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-04-16
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多