Windstorm1981
Windstorm1981

Reputation: 2680

Custom Chart Formatting in Seaborn

I have a straightforward countplot in seaborn.

Code is:

ax = sns.countplot(x="days", data=df,color ='cornflowerblue')
ax.set_xticklabels(ax.get_xticklabels(),rotation=90)
ax.set(xlabel='days', ylabel='Conversions')
ax.set_title("Days to Conversion")
for p in ax.patches:
    count = p.get_height()
    x = p.get_x() + p.get_width()/1.25
    y = p.get_height()*1.01
    ax.annotate(count, (x, y),ha='right')

Which produces:

enter image description here

I'm trying to make the chart a bit 'prettier'. Specifically I want to raise the height of the outline so it wont cross the count numbers on first bar, and make the count numbers centered with a small space about the bar. Can't get it to work.

Guidance please.

Upvotes: 0

Views: 345

Answers (1)

JohanC
JohanC

Reputation: 80319

To set the labels, in the latest matplotlib version (3.4.2), there is a new function bar_label() which takes care of positioning. In older versions you could use your code, but use x = p.get_x() + p.get_width()/2 and set ax.text(..., ha='center').

To make room for the labels, an extra margin can be added via ax.margins(y=0.1).

import matplotlib.pyplot as plt
import seaborn as sns

df = sns.load_dataset('tips')
ax = sns.countplot(x="day", data=df, color='cornflowerblue')
ax.tick_params(axis='x', labelrotation=90)
ax.bar_label(ax.containers[-1])
ax.margins(y=0.1)
plt.tight_layout()
plt.show()

sns.countplot with labels

Upvotes: 3

Related Questions