用Matplotlib调整直方图第二个坐标轴的比例

1 投票
1 回答
1503 浏览
提问于 2025-04-18 01:37

我想在我的直方图上加一个第二个坐标轴,显示每个柱子的百分比,就像我设置了normed=True一样。我试过用双坐标轴,但比例不对。

这里插入图片描述

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

如果你能让它在对数刻度的x轴上也能工作,那就更棒了 :)

1 个回答

2

plt.hist 会返回数据分成的小区间(也叫“桶”)以及每个小区间里有多少数据。你可以用这些信息来计算直方图下方的面积,然后根据这个面积来找出每个柱子的标准化高度。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

撰写回答