[英]seaborn relplot: how to control the location of the legend and add title
对于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)
在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
要理解bbox_to_anchor
的参数,请参阅matplotlib中'bbox_to_anchor'的4元素元组参数是什么意思?
同样可以应用于标题。 matplotlib参数是suptitle
。 但是我们需要图形对象。 所以我们可以使用
g.fig.suptitle("My Title")
把这一切放在一起:
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坐标(图形坐标)来更改标题的位置,以使其不与子图标题重叠
g.fig.suptitle("My Title", x=0.4, y=0.98)
虽然我可能会稍微移动您的子图并将图标题保留在其使用的位置:
plt.subplots_adjust(top=0.85)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.