Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how can I add legend in seaborn (countplot)

enter image description here
I’m trying to add a legend in this countplot. I don’t know where is the problem? why it’s not working. Will any brother help me to solve this problem?

ax=sns.countplot(x='Tomatoe types', data=df)    
ax.set_title('Tomatoe types',fontsize = 18, fontweight='bold', color='white')    
ax.set_xlabel('types', fontsize = 15, color='white')    
ax.set_ylabel('count', fontsize = 15, color='white')    
ax.legend(labels = ['Bad', 'Fresh', 'Finest']) 
for i in ax.patches:    
     ax.text(i.get_x()+i.get_width()/2, i.get_height()+0.75, i.get_height(),  
     horizontalalignment='center',size=14)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The easiest is to use hue= with the same variable as x=. You’ll need to set dodge=False as by default a position is reserved for each x – hue combination.

from matplotlib import pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np

df = pd.DataFrame({'Tomato types': np.random.choice(['bad', 'fresh', 'finest'], 200, p=[.1, .4, .5])})

ax = sns.countplot(x='Tomato types', hue='Tomato types', dodge=False, data=df)
ax.set_title('Tomato types', fontsize=18, fontweight='bold', color='white')
ax.set_xlabel('types', fontsize=15, color='white')
ax.set_ylabel('count', fontsize=15, color='white')
ax.figure.set_facecolor('0.3')

plt.tight_layout()
plt.show()

sns.countplot with legend

Note that when you aren’t using hue, no legend is added as the names and colors are given by the x tick labels.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading