Seaborn title error – AttributeError: 'FacetGrid' object has no attribute 'set_title

Question:

I created a lineplot graph to begin with using the following code:

plot = sns.lineplot(data=tips,
             x="sex",
             y="tip",
             ci=50,
             hue="day",
             palette="Accent")
plot.set_title("Value of Tips Given to Waiters, by Days of the Week and Sex", fontsize=24, pad=30, fontdict={"weight": "bold"})
plot.legend("")

I have realised that its actually a catplot chart that I need so I amended the code to the following:

plot = sns.catplot (data=tips,
             x="day",
             y="tip",
             kind='bar',
             ci=50,
             hue="sex",
             palette="Accent")
plot.set_title("Value of Tips Given to Waiters, by Days of the Week and Sex", fontsize=24, pad=30, fontdict={"weight": "bold"})
plot.legend("")

However I am getting the following error message with the title: ‘AttributeError: ‘FacetGrid’ object has no attribute ‘set_title”.

Why is my title not working for the catplot chart?

Asked By: DSouthy

||

Answers:

When you call catplot, it returns a FacetGrid object, so to change the the title and remove legend, you have to use the legend= option inside the function, and also use plot.fig.suptitle() :

import seaborn as sns
tips = sns.load_dataset("tips")
plot = sns.catplot (data=tips,
             x="day",
             y="tip",
             kind='bar',
             ci=50,
             hue="sex",
             palette="Accent", legend=False)

plot.fig.suptitle("Value of Tips Given to Waiters, by Days of the Week and Sex",
                  fontsize=24, fontdict={"weight": "bold"})

enter image description here

Answered By: StupidWolf

Same answer as @StupidWolf, but with additional adjustment for title position:

import seaborn as sns
tips = sns.load_dataset("tips")
plot = sns.catplot (data=tips,
             x="day",
             y="tip",
             kind='bar',
             ci=50,
             hue="sex",
             palette="Accent", legend=False);
plot.figure.subplots_adjust(top=0.8);
plot.figure.suptitle(
    "Value of Tips Given to Waiters, by Days of the Week and Sex",
    fontsize=24,
    fontdict={"weight": "bold"}
);
Answered By: ling
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.