Search code examples
pandasmatplotlibhistogram

Pandas histogram with legend


My dataframe looks like this:

Customer ID Age Is True
123 31 1
124 33 1
125 45 0
126 27 0
127 37 1
128 39 0
129 49 0
130 30 0
131 30 0
132 38 1

I can create age histogram like this:

df.Age.hist()
plt.title('Age')
plt.xlabel('Age')
plt.ylabel('Frequency')

And I will get:

enter image description here

I would like to add a legend of the 'Is True' field. For each Bin, I would like to see what portion is 1. How can I do that?


Solution

  • I'm not sure you can do that with Matplotlib. But I know you can with Plotly.

    import plotly.express as px
    df = px.data.tips()
    fig = px.histogram(df, x="total_bill", color="sex")
    fig.show()
    

    enter image description here

    more here: https://plotly.com/python/histograms/