我想在我的直方图上有第二个斧头,与每个箱相对应的倾注率,就像我使用normed=True一样。我尝试使用双胞胎,但比例不正确。
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)
关于python - 使用 Matplotlib 缩放直方图上的第二个轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22898074/