简体   繁体   中英

seaborn relplot: how to control the location of the legend and add title

For python relplot, how to control the location of legend and add a plot title? I tried plt.title('title') but it doesn't work.

import seaborn as sns

dots = sns.load_dataset("dots")

# Plot the lines on two facets
sns.relplot(x="time", y="firing_rate",
            hue="coherence", size="choice", col="align",
            size_order=["T1", "T2"], 
            height=5, aspect=.75, facet_kws=dict(sharex=False),
            kind="line", legend="full", data=dots)

A typical way of changing the location of a legend in matplotlib is to use the arguments loc and bbox_to_anchor .
In Seaborn's relplot a FacetGrid object is returned. In order to get the legend object we can use _legend . We can then set the loc and bbox_to_anchor :

g = sns.relplot(...)

leg = g._legend
leg.set_bbox_to_anchor([0.5, 0.5])  # coordinates of lower left of bounding box
leg._loc = 2  # if required you can set the loc

To understand the arguments of bbox_to_anchor see What does a 4-element tuple argument for 'bbox_to_anchor' mean in matplotlib?

The same can be applied to the title. The matplotlib argument is suptitle . But we need the figure object. So we can use

g.fig.suptitle("My Title")

Putting this all together:

import seaborn as sns

dots = sns.load_dataset("dots")

# Plot the lines on two facets
g = sns.relplot(x="time", y="firing_rate",
            hue="coherence", size="choice", col="align",
            size_order=["T1", "T2"],
            height=5, aspect=.75, facet_kws=dict(sharex=False),
            kind="line", legend="full", data=dots)

g.fig.suptitle("My Title")

leg = g._legend
leg.set_bbox_to_anchor([1,0.7])  # change the values here to move the legend box
# I am not using loc in this example

在此输入图像描述

Update
You can change the position of the title by providing the x and y coordinates (figure coordinates) so that it doesn't overlap the subplot titles

g.fig.suptitle("My Title", x=0.4, y=0.98)

Although I would probably move your subplots down slightly and leave the figure title where it is using:

plt.subplots_adjust(top=0.85)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM