【问题标题】:what is the right way to plot a histogram in python using pyplot使用pyplot在python中绘制直方图的正确方法是什么
【发布时间】:2021-12-01 09:23:55
【问题描述】:

我在网上看到了两种方法,但是在尝试了这两种方法之后,您会认为图应该看起来一样,但实际上并不一样。

方法一:

n, bins, patches = plt.hist(SP[0], 30, facecolor='green', alpha=1, histtype='stepfilled')

方法二:

counts, bins = np.histogram(SP[0])
plt.hist(bins[:-1], bins=30, weights=counts)

【问题讨论】:

  • 输入似乎是离散的,而plt.hist 用于连续数据。因此,您的第一个直方图格式不正确。对于您的第二个绘图,除了使用错误的bin= 参数外,如果您真的想使用weights=,您会遇到舍入问题。

标签: python matplotlib histogram


【解决方案1】:

这两种方法做的事情完全不同。 Method1 是正确的。 plt.hist() 计算其第一个参数的直方图并绘制结果。
方法2根本有错误。您首先通过np.histogram() 计算您的直方图,然后绘制结果。但是您不要在第二步中使用plt.hist()。如果这样做,您将绘制之前函数调用的结果直方图的 bin 的直方图。相反,您只需使用plt.plot()plt.step()。我建议你使用:

counts, bins = np.histogram(SP[0], bins=30)
plt.step(bins[:-1], counts, where='post')

【讨论】:

  • 也可以使用plt.bar 绘制np.histogram 的结果
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-25
  • 2018-07-23
  • 1970-01-01
相关资源
最近更新 更多