【问题标题】:Scaling the second axe on a histogram with Matplotlib使用 Matplotlib 在直方图上缩放第二轴
【发布时间】:2014-04-06 18:24:44
【问题描述】:

我想在我的直方图上有第二个轴,与每个 bin 对应的 pourcentage,就像我使用 normed=True 一样。我尝试使用双胞胎,但比例不正确。

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

如果你可以让它与 log scaled x 一起工作,那么奖励点 :)

【问题讨论】:

    标签: python matplotlib histogram


    【解决方案1】:

    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)
    

    【讨论】:

    • 不确定您是否会阅读我的评论,但 oyu 如何获得这些颜色?
    猜你喜欢
    • 1970-01-01
    • 2017-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多