Search code examples
pythonmatplotlibbar-chartlegendsubplot

Barplot subplot legend python


Hello everyone how can i make legend for 3 different bar color that code with subplot? Data frame:

enter image description here

This is my code:

fig,axs = plt.subplots(2,3, figsize=(30,20))
axs[0,1].bar(x = df_7_churn_tenure['Kategori'],height = df_7_churn_tenure['Jumlah Churn'],color = ['lightsalmon','maroon','darkorange'])
axs[0,1].legend(['Low Tenure = x<24','Medium Tenure = 24<= x <=48','High Tenure = x >=48'],loc='best',fontsize=12)
plt.show()

And the result for barplot legend only shows 1 label like this:

enter image description here

Is there any solution to shows all of my legend?


Solution

  • Try this:
    
    fig,axs = plt.subplots(2,3, figsize=(30,20))
    axs[0,1].bar(x = df_7_churn_tenure['Kategori'],height = df_7_churn_tenure['Jumlah Churn'],color ['lightsalmon','maroon','darkorange'])
    
    axs = axs[0,1]
    lns1 = axs.plot('-',label = 'Low Tenure = x<24')
    lns2 = axs.plot('-',label = 'Medium Tenure = 24<= x <=48')
    lns3 = axs.plot('-',label = 'High Tenure = x >=48')
    
    # added these three lines
    lns = lns1+lns2+lns3
    labs = [l.get_label() for l in lns]
    axs.legend(lns, labs,loc=0)
    plt.show()