【发布时间】:2020-09-24 08:56:54
【问题描述】:
seaborn 等一些绘图工具会自动标记绘图并添加图例。使用ax.get_legend().remove() 删除图例相当容易,但句柄和标签仍存储在轴对象中的某个位置。因此,当添加另一条线或其他绘图类型时,我想要为其添加一个图例,“旧”图例句柄和标签也会显示。换句话说:ax.get_legend_handles_labels() 仍然返回 f.i. 引入的标签和句柄。海生。
有没有办法完全删除轴上用于图例的句柄和标签?
这样ax.get_legend_handles_labels() 返回([], [])?
我知道我可以在 seaborn 中设置sns.lineplot(..., legend=False)。我只是在使用 seaborn 来制作一个很好的例子。问题是一般如何移除现有的图例标签和句柄。
这是一个最小的工作示例:
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
df = pd.DataFrame(data={
'x': [0, 1, 0, 1],
'y': [7.2, 10., 11.2, 3.],
'id': [4, 4, 7, 7]
})
# get mean per x location:
grpd = df.groupby('x').mean()
ax = sns.lineplot(data=df, x='x', y='y', hue='id', palette=['b', 'g'])
ax.get_legend().remove()
# this still returns the handles and labels:
print(ax.get_legend_handles_labels())
# Out:
# ([<matplotlib.lines.Line2D at 0x17c1c208f88>,
# <matplotlib.lines.Line2D at 0x17c1c1f8888>,
# <matplotlib.lines.Line2D at 0x17c1c20af88>],
# ['id', '4', '7'])
# plot some other lines, for which I want to have a legend:
ax.plot(grpd.index, grpd['y'], label='mean')
# add legend, ONLY FOR MEAN, if possible:
ax.legend()
我尝试操作坐标轴 ax.get_legend() 和 ax.legend_ 对象,f.i.使用ax.legend_.legendHandles = [],设置标签、文本和其他所有内容,但“旧”的 seaborn 条目每次都会重新出现。
由于这是在模块中使用的,因此不适用明确设置仅包含“均值”条目的图例。我需要“清除”后端发生的所有事情,以便为用户提供干净的 API。
【问题讨论】:
标签: python matplotlib seaborn