How to Increase the Font Size of the Legend in My Seaborn Factorplot/Facetgrid

How to increase the font size of the legend in my Seaborn FactorPlot/FacetGrid?

As in the linked answer you may use setp to set the properties (in this case the fontsize of the legend).

The only difference to the linked question is that you need to do that for each axes of the FacetGrid

g = FacetGrid( ... )

for ax in g.axes.flat:
plt.setp(ax.get_legend().get_texts(), fontsize=22) # for legend text
plt.setp(ax.get_legend().get_title(), fontsize=32) # for legend title

how to change legend font size of FacetGrid plot?

You can access the legend from the FacetGrid that sns.displot returns with FacetGrid.legend. Then you can modify the text elements like so:

import seaborn as sns

tips = sns.load_dataset("tips")

g = sns.displot(data=tips, x="total_bill", hue="day")

# Legend title
g.legend.get_title().set_fontsize(20)

# Legend texts
for text in g.legend.texts:
text.set_fontsize(20)

displot with larger legend text

How to increase the font size of the legend in my Seaborn plot?

Use matplotlib function setp according to this example:

import seaborn as sns
import matplotlib.pylab as plt
sns.set_style("whitegrid")
tips = sns.load_dataset("tips")

ax = sns.stripplot(x="sex", y="total_bill", hue="day", data=tips, jitter=True)
plt.setp(ax.get_legend().get_texts(), fontsize='22') # for legend text
plt.setp(ax.get_legend().get_title(), fontsize='32') # for legend title

plt.show()

enter image description here

Another way is to change font_scale of all graph with plotting_context:
http://seaborn.pydata.org/generated/seaborn.plotting_context.html

How can I change the font size using seaborn FacetGrid?

You can scale up the fonts in your call to sns.set().

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
x = np.random.normal(size=37)
y = np.random.lognormal(size=37)

# defaults
sns.set()
fig, ax = plt.subplots()
ax.plot(x, y, marker='s', linestyle='none', label='small')
ax.legend(loc='upper left', bbox_to_anchor=(0, 1.1))

enter image description here

sns.set(font_scale=5)  # crazy big
fig, ax = plt.subplots()
ax.plot(x, y, marker='s', linestyle='none', label='big')
ax.legend(loc='upper left', bbox_to_anchor=(0, 1.3))

enter image description here

Increase tick label font size in seaborn

The answer from here makes fonts larger in seaborn ...

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

# Generate data
df = pd.DataFrame({"Draughts": np.random.randn(100)})

# Plot using seaborn
sns.set(font_scale = 2)
b = sns.violinplot(y = "Draughts", data = df)
plt.show()

enter image description here

How to edit a seaborn legend title and labels for figure-level functions

  • If legend_out is set to True then legend is available through the g._legend property and it is a part of a figure. Seaborn legend is standard matplotlib legend object. Therefore you may change legend texts.
  • Tested in python 3.8.11, matplotlib 3.4.3, seaborn 0.11.2
import seaborn as sns

# load the tips dataset
tips = sns.load_dataset("tips")

# plot
g = sns.lmplot(x="total_bill", y="tip", hue="smoker", data=tips, markers=["o", "x"], facet_kws={'legend_out': True})

# title
new_title = 'My title'
g._legend.set_title(new_title)
# replace labels
new_labels = ['label 1', 'label 2']
for t, l in zip(g._legend.texts, new_labels):
t.set_text(l)

Sample Image

Another situation if legend_out is set to False. You have to define which axes has a legend (in below example this is axis number 0):

g = sns.lmplot(x="total_bill", y="tip", hue="smoker", data=tips, markers=["o", "x"], facet_kws={'legend_out': False})

# check axes and find which is have legend
leg = g.axes.flat[0].get_legend()
new_title = 'My title'
leg.set_title(new_title)
new_labels = ['label 1', 'label 2']
for t, l in zip(leg.texts, new_labels):
t.set_text(l)

Sample Image

Moreover you may combine both situations and use this code:

g = sns.lmplot(x="total_bill", y="tip", hue="smoker", data=tips, markers=["o", "x"], facet_kws={'legend_out': True})

# check axes and find which is have legend
for ax in g.axes.flat:
leg = g.axes.flat[0].get_legend()
if not leg is None: break
# or legend may be on a figure
if leg is None: leg = g._legend

# change legend texts
new_title = 'My title'
leg.set_title(new_title)
new_labels = ['label 1', 'label 2']
for t, l in zip(leg.texts, new_labels):
t.set_text(l)

Sample Image

This code works for any seaborn plot which is based on Grid class.

Seaborn Facet Grid legend overlapping

Your problem stems from the use of plt.tight_layout(), which tries to adjust the margins of the axes to make sure that all labels are visible, but is not aware of the space required for the legend.

As you noted, if you remove plt.tight_layout(), FacetGrid leaves room for the legend on the right, but your x-labels are sticking out of the figure because of the rotation. So my advice would be to leave the layout from FacetGrid, but make more room for your x-tick labels using plt.subplots_adjust(bottom=0.25)

grid.map(sns.lineplot, 'transaction_date', 'units', alpha=0.5).add_legend()
grid.fig.set_size_inches(plt.rcParams['figure.figsize'])
plt.tight_layout()
# include_zero_on_y_axis(grid)
plt.show()

g = sns.FacetGrid(df, hue='Floor', col="Month", sharex=False, sharey=True)
g.map(sns.lineplot, "Date_Time", "Occlusion", legend="full")

for ax in g.axes.flatten():
ax.set_xticklabels(ax.get_xticklabels(), rotation=90)
ax.xaxis.set_major_formatter(dates.DateFormatter("%H:%M"))
ax.set_xticks(ax.get_xticks()[::2])

l = g.add_legend()
g.set_axis_labels("Hour", "Occlusion")
g.set(ylim=(0, 1.0))
plt.suptitle('Northeast', y=0.98, fontsize=14)
plt.subplots_adjust(bottom=0.25)
plt.show()

Sample Image

Overriding Seaborn legend

regplot is a figure-level function, and returns a FacetGrid. You can remove its legend via g.legend.remove().

import matplotlib.pyplot as plt
import seaborn as sns

tips = sns.load_dataset("tips")
g = sns.relplot(data=tips, x="total_bill", y="tip", hue="day")
g.legend.remove()
plt.legend(['Jeudi', 'Vendredi', 'Samedi', 'Dimanche'])
plt.show()

resulting plot

This code has been tested with seaborn 0.11. Possibly you'll need to upgrade. To add a title to the legend: plt.legend([...], title='New title').

Note that plt.legend(...) will create the legend inside the last (or only) subplot. If you prefer the figure-level legend next to the plot, to change the legend labels, you can call g.add_legend(labels=[...], title='new title') after having removed the old legend.

PS: Adding legend=False to sns.relplot() will not create the legend entries. So, you'll need to recreate both the legend markers and their labels, while you lost the information of which colors were used.



Related Topics



Leave a reply



Submit