对于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)
答案 0 :(得分:4)
在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
的参数,请参见What does a 4-element tuple argument for 'bbox_to_anchor' mean in matplotlib?
可以对标题应用相同的内容。 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)