首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >seaborn relplot:如何控制图例的位置和添加标题

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

Stack Overflow用户
提问于 2019-01-16 11:10:31
回答 1查看 12.6K关注 0票数 7

对于python relplot,如何控制图例的位置和添加绘图标题?我尝试过plt.title('title'),但它不起作用。

代码语言:javascript
运行
复制
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)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-01-16 17:27:46

在matplotlib中更改图例位置的典型方法是使用参数locbbox_to_anchor

在Seaborn的relplot中,会返回一个FacetGrid对象。为了获得图例对象,我们可以使用_legend。然后,我们可以设置locbbox_to_anchor

代码语言:javascript
运行
复制
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

要理解bbox_to_anchor的参数,请参阅What does a 4-element tuple argument for 'bbox_to_anchor' mean in matplotlib?

同样的情况也可以应用于标题。matplotlib参数是suptitle。但我们需要图形对象。所以我们可以使用

代码语言:javascript
运行
复制
g.fig.suptitle("My Title")

把所有这些放在一起:

代码语言:javascript
运行
复制
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

更新

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

代码语言:javascript
运行
复制
g.fig.suptitle("My Title", x=0.4, y=0.98)

虽然我可能会将你的子图稍微向下移动,而把图标题留在它使用的地方:

代码语言:javascript
运行
复制
plt.subplots_adjust(top=0.85)
票数 15
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54209895

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档