seaborn relplot:如何控制图例的位置并添加标题

san*_*oku 5 python plot matplotlib seaborn

对于python relplot,如何控制图例的位置并添加图标题?我试过了,plt.title('title')但是没有用。

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)
Run Code Online (Sandbox Code Playgroud)

Dav*_*idG 6

在matplotlib中更改图例位置的一种典型方法是使用参数loc和bbox_to_anchor。
在Seaborn relplot中,返回了FacetGrid对象。为了获得图例对象,我们可以使用_legend。然后我们可以设置loc和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
Run Code Online (Sandbox Code Playgroud)

了解bbox_to_anchorsee 的论点 matplotlib中'bbox_to_anchor'的4元素元组参数是什么意思?

标题同样适用。matplotlib参数为suptitle。但是我们需要图形对象。所以我们可以使用

g.fig.suptitle("My Title")
Run Code Online (Sandbox Code Playgroud)

全部放在一起:

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
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

更新
您可以通过提供x和y坐标(图坐标)来更改标题的位置,以使其不与子图标题重叠

g.fig.suptitle("My Title", x=0.4, y=0.98)
Run Code Online (Sandbox Code Playgroud)

尽管我可能会稍微下移您的子图,然后将图形标题保留在使用的位置:

plt.subplots_adjust(top=0.85)
Run Code Online (Sandbox Code Playgroud)