seaborn displot绘制分组KDE图时修改图例标题报错问题
问题描述
绘制三个类别对应的变量分布时,图表可正常生成,但修改图例标题的操作始终不生效,运行时抛出对应报错,未定位到遗漏的配置项。
复现代码
import os import pandas as pd import seaborn as sb import matplotlib.pyplot as plt df = pd.read_csv(os.path.join(data_path, "test.csv")) distplot = sb.displot(df, x="depth", hue="label", kind="kde") distplot.fig.legend(title='Node type') plt.show(block=True)
运行报错
No artists with labels found to put in legend. Note that artists whose label start with an underscore are ignored when legend() is called with no argument.
测试数据
label,depth A,1 A,2 A,3 B,1 B,1 B,4 B,4 B,4 C,1 C,2 C,6 C,6 C,6
问题原因
sb.displot 是Seaborn的Figure级绘图函数,返回的是FacetGrid对象,自动生成的图例默认绑定在网格的子图(Axes)对象上。直接调用distplot.fig.legend()且不传入绘图元素参数时,会尝试在Figure层面创建全新的空图例,找不到任何带有效标签的绘图元素,就会触发上述报错,也无法修改原有图例的标题。
解决方案
- 方案1(最简便,代码改动最小):直接操作FacetGrid自带的图例属性修改标题,无需新建图例,不会触发报错:
df = pd.read_csv(os.path.join(data_path, "test.csv")) distplot = sb.displot(df, x="depth", hue="label", kind="kde") # 直接修改现有图例的标题 distplot.legend.set_title('Node type') plt.show(block=True)
- 方案2(需自定义图例位置时使用):先提取原有图例的绘图元素,再在Figure层面创建新图例,注意移除子图上的默认图例避免重复显示:
df = pd.read_csv(os.path.join(data_path, "test.csv")) distplot = sb.displot(df, x="depth", hue="label", kind="kde") # 提取已有图例的句柄和标签 handles, labels = distplot.axes[0][0].get_legend_handles_labels() # 移除子图上的默认图例 distplot.axes[0][0].get_legend().remove() # 创建带自定义标题的Figure级图例 distplot.fig.legend(handles=handles, labels=labels, title='Node type', loc="upper right") plt.show(block=True)
内容的提问来源于stack exchange,提问作者Tobias
相关产品推荐
相关产品推荐

