对于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)
发布于 2019-01-16 17:27:46
在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)
https://stackoverflow.com/questions/54209895
复制相似问题