python - 使用 Matplotlib 缩放直方图上的第二个轴

标签 python matplotlib histogram

我想在我的直方图上有第二个斧头,与每个箱相对应的倾注率,就像我使用normed=True一样。我尝试使用双胞胎,但比例不正确。

enter image description here

x = np.random.randn(10000)
plt.hist(x)
ax2 = plt.twinx()
plt.show()

如果你能让它与对数缩放 x 一起工作,那就加分了:)

最佳答案

plt.hist 返回 bin 以及每个存储桶中的数据数量。您可以使用它们来计算直方图下的面积,并使用它您可以找到每个条形的标准化高度。 twinx 轴可以相应地对齐:

xs = np.random.randn(10000)
ax1 = plt.subplot(111)
cnt, bins, patches = ax1.hist(xs)

# area under the istogram
area = np.dot(cnt, np.diff(bins))

ax2 = ax1.twinx()
ax2.grid('off')

# align the twinx axis
ax2.set_yticks(ax1.get_yticks() / area)
lb, ub = ax1.get_ylim()
ax2.set_ylim(lb / area, ub / area)

# display the y-axis in percentage
from matplotlib.ticker import FuncFormatter
frmt = FuncFormatter(lambda x, pos: '{:>4.1f}%'.format(x*100))
ax2.yaxis.set_major_formatter(frmt)

enter image description here

关于python - 使用 Matplotlib 缩放直方图上的第二个轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22898074/

相关文章:

python - Kafka消费者使用python进行轮询消息

python - Matplotlib:分配不同的颜色

python - 在 matplotlib 中设置可变点大小

python - 使用 seaborn jointplot 更改每个点的颜色和标记

javascript - 使用 d3 将累积百分比线拟合到排序后的直方图输出,以获得帕累托图直方图

计算推土机距离的Java代码/库

python - 在直方图中绘制 x-ticks matplotlib

python - 自一天 UTC 时区开始以来的秒数

python - Django加载什么模板?

javascript - 对于给定的正则表达式,R 正则表达式编译器的工作方式不同