python-3.x - 获取 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
几分钟前我已经成功执行了,但没有任何结果。
如何自动放置我的评论?
解决方案
感谢@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')
推荐阅读
- html - 第一个站点页面显示到第二个站点
- go - golang解析2s补码二进制字符串
- php - 网络数据传输和 API
- python-3.x - 在 Mac 上的 IDLE 中使用 Python 时鼠标指针未对齐
- html - Hơ 在访问 Windows 10 热点后自动启动网站
- reactjs - React Redux 订阅方法以指数方式触发?
- flutter - 为什么 Text 小部件的行高从英文变为中文?
- java - 为什么将 == 与 Enum.toString() 一起使用?
- react-native - 将本机自定义字体反应为默认系统字体?
- android - Android Gyro,幻影“防漂移”,导致读数大乱