pythonseabornlegendcountplot

How can I add a legend to 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

  • 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.