【问题标题】:Matplotlib histogram does not show details of distributionMatplotlib 直方图不显示分布细节
【发布时间】:2019-07-11 04:48:22
【问题描述】:

我有一些数据,我想看看它的分布。但我不知道为什么当我使用这段代码时,直方图并没有真正显示数据中发生的事情,而是显示了一个非常笼统的画面。我想要一个更细粒度的直方图。

data['feature'].plot(kind='hist')

这就是这段代码给我的:

直方图:

我怎样才能使它更细化?

【问题讨论】:

  • 看matplotlib.pyplot.hist的bins参数:matplotlib.org/api/_as_gen/matplotlib.pyplot.hist.html
  • 尝试将bins=32 传递给.plot()(或其他数字)
  • 欢迎来到 SO。在不知道您要绘制的内容(示例数据/输入)的情况下,将很难提供帮助。请阅读minimal reproducible example、How to Ask 以及该页面上的其他链接。
  • 我的数据有10000条记录。我真的不能在这里打字。但大多在 0 到 5 之间,也有一些值在 10、20、30 和更大的范围内

标签: python pandas dataframe matplotlib histogram


【解决方案1】:

bins 参数将采用一系列 bin 边缘并支持不等间距的 bin。构建一个序列,为您的大部分数据提供更精细的粒度

data['feature'].plot(kind='hist', bins=[0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,
                                        1.0,...
                                        9.1,9.2,9.3,9.4,9.5,9.6,9.7,9.8,9.9,10,
                                        20, 30)  

或

data.plot.hist(by='feature', bins=[0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,
                                   1.0,...
                                   9.1,9.2,9.3,9.4,9.5,9.6,9.7,9.8,9.9,
                                   10, 20, 30)

您可以使用 numpy.linspace 和 numpy.concatenate 制造 bins 参数:

bins = np.concatenate((np.linspace(0,10,num=101), [20,30]))

【讨论】:

  • 太棒了。谢谢
  • 投反对票会很好,这样我就可以纠正/减轻缺陷。
【解决方案2】:

data['feature'].plot(kind='hist', bins=100)

这会将直方图分为 100 个 bin。如果您需要更高的粒度,您自然可以使用更高的数字。


您的数据似乎很偏左。您可以使用 pd.qcut 作为 bins 参数强制 100 个具有相同成员数的 bin:

_, bins = pd.qcut(data['feature'], 100, retbins=True) data['feature'].plot(kind='hist', bins=bins)

【讨论】:

  • 这并没有解决问题,只是让直方图变薄了
  • 您能否发布您正在处理的 ghe 数据示例?似乎您的数据非常偏左。您可以将logx=True 参数传递给函数。
猜你喜欢
  • 2021-02-15
  • 2016-08-29
  • 1970-01-01
  • 2018-02-08
  • 2020-01-24
  • 1970-01-01
  • 1970-01-01
  • 2017-04-28
  • 1970-01-01
相关资源
最近更新 更多