更改Python柱状图bin中的计数

2024-03-28 19:19:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Python直方图。在

我想将直方图的峰值归一化为1,这样只有条的相对高度才是重要的。在

我看到一些方法,包括改变箱子的宽度,但我不想这样做。在

我也意识到我可以改变y轴的标签,但我也有另一个重叠的图,所以yticks必须是实际值。在

难道没有办法访问和更改每个箱子的直方图“计数”?在

谢谢。在


Tags: 方法宽度标签直方图计数意识峰值办法
1条回答
网友
1楼 · 发布于 2024-03-28 19:19:49

我想你想要的是一个标准化的直方图,其中y轴是密度而不是计数。如果使用的是Numpy,只需使用histogram function中的normed标志。在

如果希望直方图的峰值为1,则可以将每个bin中的计数除以最大bin值,即(根据SO MatPlotLib示例here)除以:

#!/usr/bin/env python
import matplotlib.pyplot as plt
import numpy as np

# Generate random data
mu, sigma = 200, 25
x = mu + sigma*np.random.randn(10000)

# Create the histogram and normalize the counts to 1
hist, bins = np.histogram(x, bins = 50)
max_val = max(hist)
hist = [ float(n)/max_val for n in hist]

# Plot the resulting histogram
center = (bins[:-1]+bins[1:])/2
width = 0.7*(bins[1]-bins[0])
plt.bar(center, hist, align = 'center', width = width)
plt.show()

enter image description here

相关问题 更多 >