首页 > 解决方案 > 获取 Seaborn 传奇位置

问题描述

我想在我的图例下添加评论。这是一个执行我想要的示例代码:

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'

(这与这个已关闭的问题非常相似)

我运行 MacOS Catalina 10.15.4 版,conda update --all几分钟前我已经成功执行了,但没有任何结果。

如何自动放置我的评论?

标签: python-3.xmatplotlibseabornlegend-properties

解决方案


感谢@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')

推荐阅读