0
votes

There is the following code which produces a countplot with seaborn and annotating the precentage:

ax = sns.countplot(y=target_column, data=data, hue=target_column)
plt.title(f'Distribution of {target_column}')
plt.xlabel('Number of occurrences')

total = len(data[target_column])
for p in ax.patches:
    percentage = '{:.1f}%'.format(100 * p.get_width()/total)
    x = p.get_x() + p.get_width() + 0.02
    y = p.get_y() + p.get_height()/2
    ax.annotate(percentage, (x, y))

I wanted to add a legend and I know there is the hue parameter, but the result is that the legend box is overlapping the actual my bar and the percent annotation:

enter image description here

How do I change the location of the legend to the bottom-right of the plot?

2

2 Answers

1
votes

I do not have your data to try but plt.legend(loc='lower left') as in https://matplotlib.org/3.2.1/api/_as_gen/matplotlib.pyplot.legend.html should do the job (btw that's where you have it now, maybe you want lower right).

0
votes

You might also want to let the legend choose the best location in terms of space using

ax = sns.countplot(y=target_column, data=data, hue=target_column)
ax.legend(loc='best')