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

旧街凉风 提交于 2020-12-25 04:16:08

问题


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)

回答1:


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)


来源:https://stackoverflow.com/questions/54209895/seaborn-relplot-how-to-control-the-location-of-the-legend-and-add-title

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!