python - Scaling the second axe on a histogram with Matplotlib -
i want have second axe on histogram, pourcentage corresponding each bin, if used normed=true. tried use twins, scale not correct.
x = np.random.randn(10000) plt.hist(x) ax2 = plt.twinx() plt.show()
bonus point if can make work log scaled x :)
plt.hist
returns bins , number of data in each bucket. may use these compute area under histogram, , using may find normalized height of each bar. twinx
axis can aligned accordingly:
xs = np.random.randn(10000) ax1 = plt.subplot(111) cnt, bins, patches = ax1.hist(xs) # area under istogram area = np.dot(cnt, np.diff(bins)) ax2 = ax1.twinx() ax2.grid('off') # align twinx axis ax2.set_yticks(ax1.get_yticks() / area) lb, ub = ax1.get_ylim() ax2.set_ylim(lb / area, ub / area) # display y-axis in percentage matplotlib.ticker import funcformatter frmt = funcformatter(lambda x, pos: '{:>4.1f}%'.format(x*100)) ax2.yaxis.set_major_formatter(frmt)
Comments
Post a Comment