获取 Seaborn 图例位置
Get Seaborn legend location
我想在我的图例下添加评论。这是一个做我想做的示例代码:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
df1 = pd.DataFrame(np.random.normal(size=100))
df2 = pd.DataFrame(np.random.uniform(size=100))
fig,ax=plt.subplots()
sns.distplot(df1,ax=ax,label='foo')
sns.distplot(df2,ax=ax,label='bar')
hardlocy = 0.92
xmargin=0.02
xmin,xmax = ax.get_xlim()
xtxt=xmax-(xmax-xmin)*xmargin
leg = ax.legend()
plt.text(xtxt,hardlocy,"Comment",
horizontalalignment='right'
);
结果是:
如您所见,我依赖于手动位置设置,至少对于 y 轴。我想自动完成。
根据 and ,我尝试通过p = leg.get_window_extent()
访问图例特征,但我收到以下错误消息:
AttributeError: 'NoneType' object has no attribute 'points_to_pixels'
(与this closed issue非常相似)
我运行MacOS Catalina version 10.15.4并且我在几分钟前conda update --all
执行成功,没有任何结果。
如何自动放置我的评论?
感谢@JohanC,来自:
需要画图才能算出图例。因此,这里的工作代码可能是:
np.random.seed(0)
df1 = pd.DataFrame(np.random.normal(size=100))
df2 = pd.DataFrame(np.random.uniform(size=100))
fig,ax=plt.subplots()
sns.distplot(df1,ax=ax,label='foo')
sns.distplot(df2,ax=ax,label='bar')
ymargin=0.05
leg = ax.legend()
fig.canvas.draw()
bbox = leg.get_window_extent()
inv = ax.transData.inverted()
(xloc,yloc)=inv.transform((bbox.x1,bbox.y0))
ymin,ymax = ax.get_ylim()
yloc_margin=yloc-(ymax-ymin)*ymargin
ax.text(xloc,yloc_margin,"Comment",horizontalalignment='right')
我想在我的图例下添加评论。这是一个做我想做的示例代码:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
df1 = pd.DataFrame(np.random.normal(size=100))
df2 = pd.DataFrame(np.random.uniform(size=100))
fig,ax=plt.subplots()
sns.distplot(df1,ax=ax,label='foo')
sns.distplot(df2,ax=ax,label='bar')
hardlocy = 0.92
xmargin=0.02
xmin,xmax = ax.get_xlim()
xtxt=xmax-(xmax-xmin)*xmargin
leg = ax.legend()
plt.text(xtxt,hardlocy,"Comment",
horizontalalignment='right'
);
结果是:
如您所见,我依赖于手动位置设置,至少对于 y 轴。我想自动完成。
根据p = leg.get_window_extent()
访问图例特征,但我收到以下错误消息:
AttributeError: 'NoneType' object has no attribute 'points_to_pixels'
(与this closed issue非常相似)
我运行MacOS Catalina version 10.15.4并且我在几分钟前conda update --all
执行成功,没有任何结果。
如何自动放置我的评论?
感谢@JohanC,来自
需要画图才能算出图例。因此,这里的工作代码可能是:
np.random.seed(0)
df1 = pd.DataFrame(np.random.normal(size=100))
df2 = pd.DataFrame(np.random.uniform(size=100))
fig,ax=plt.subplots()
sns.distplot(df1,ax=ax,label='foo')
sns.distplot(df2,ax=ax,label='bar')
ymargin=0.05
leg = ax.legend()
fig.canvas.draw()
bbox = leg.get_window_extent()
inv = ax.transData.inverted()
(xloc,yloc)=inv.transform((bbox.x1,bbox.y0))
ymin,ymax = ax.get_ylim()
yloc_margin=yloc-(ymax-ymin)*ymargin
ax.text(xloc,yloc_margin,"Comment",horizontalalignment='right')