riskiem
riskiem

Reputation: 307

How to add legend to a histogram?

I have a histogram of fee_rate broken down by sex stored in a data frame called fees.

To plot the same I used the following code:

axarr = fees.hist(column='fee_rate', by = 'gender')


for ax in axarr.flatten():
 ax.set_xlabel("fee_rate")
 ax.legend(gender)

I need to have a legend on the plot which says the plot is by for male or female. However using the above code, I get "Female" on both the plots. Can someone point out the error?

Upvotes: 0

Views: 1805

Answers (2)

pakpe
pakpe

Reputation: 5479

The appropriate legend for these two plots is not the sex, but the word 'tip_rate', since that's what's being plotted. The sex is already being displayed as the title of each subplot. You can verify this by setting the legend = True. If you choose to do this, you can get rid of your loop which labels the x_axis. Alternatively, you can forget about the legend altogether and use you loop to label the x_axis.

tips.hist(column='tip_rate', by = 'sex',legend=True)
plt.suptitle('TIP RATES BY SEX')
plt.show()

enter image description here

Upvotes: 1

Vons
Vons

Reputation: 3325

  • It appears as if the titles already indicate that the left graph is for females and the right for males. So one option would be to leave out the legend altogether.

  • If you insist on having a legend on top of that, you can try ax.legend((ax.get_title(),)).

Upvotes: 0

Related Questions