matplotlib 2 y-axes histogram with percentage from total on the right and frequency on the left

24 Views Asked by At

I want to create 2 histograms on the plot. Female vs Male purchases. I would like to see 2 y-axes - right is frequency, left percentage from total. Based on the internet I managed to create this plot

fig,ax = plt.subplots()
ax.hist(bf_sales[bf_sales.Gender =='M']['Purchase']);
ax.hist(bf_sales[bf_sales.Gender =='F']['Purchase']);

ax2 = ax.twinx()
ax2.hist(bf_sales[bf_sales.Gender =='M']['Purchase'], weights =[1/len(bf_sales[bf_sales.Gender =='M']['Purchase'])] * len(bf_sales[bf_sales.Gender =='M']['Purchase']))
plt.gca().yaxis.set_major_formatter(PercentFormatter(1))

But the plot is not aligned. This is the result. It would be perfectly if the second plot ax2 wouldn't be at all drawn only y-axis.

0

There are 0 best solutions below