seaborn relplot:如何控制图例的位置并添加标题 [英] seaborn relplot: how to control the location of the legend and add title
问题描述
对于python relplot,如何控制图例的位置并添加图标题?我试过 plt.title('title')
但它不起作用.
导入 seaborn 为 sns点= sns.load_dataset(点")# 在两个面上绘制线条sns.relplot(x="time", y="firing_rate",色调=连贯性",大小=选择",列=对齐",size_order=["T1", "T2"],高度=5,方面=.75,facet_kws=dict(sharex=False),kind ="line",legend ="full",data =点)
更改matplotlib中图例位置的一种典型方法是使用参数 loc
和 bbox_to_anchor
.
在Seaborn的
更新
您可以通过提供 x 和 y 坐标(图形坐标)来更改标题的位置,使其不与子图标题重叠
g.fig.suptitle("我的标题", x=0.4, y=0.98)
尽管我可能会稍微向下移动您的子图并将图形标题保留在它使用的位置:
plt.subplots_adjust(top = 0.85)
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)
这篇关于seaborn relplot:如何控制图例的位置并添加标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!