Python子图添加图例异常:仅显示首字母问题求助
解决Matplotlib子图图例仅显示首字母的问题
嘿,我之前也踩过这个坑!这种情况基本是因为你没正确给图例指定要关联的绘图元素(也就是句柄handles),导致Matplotlib错误地把你的图例标签字符串拆成单个字符处理,自然就只显示首字母了。
问题根源
seaborn.distplot会一次性创建多个绘图元素——比如直方图的矩形补丁、拟合的密度曲线等。如果直接调用ax.legend()却不指定具体要关联哪个元素,Matplotlib的自动识别逻辑会混乱,把标签字符串的每个字符当成独立的图例项,最终只显示第一个字符。
修复方案(针对你用的distplot)
修改你的代码,明确提取需要的绘图句柄(比如拟合的正态曲线),再和标签一起传给legend():
import seaborn as sns import matplotlib.pyplot as plt from scipy.stats import norm # 假设target是你的目标变量数组 fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(20,10)) # 第一个子图:SalePrice的正态分布 # 获取distplot返回的绘图对象(包含曲线、补丁等元素) normal_plot = sns.distplot(target, ax=ax[0]) ax[0].set_title('Normal SalePrice Distribution') norm_mu, norm_sigma = norm.fit(target) norm_legend = f'Normal dist. ($\mu=$ {norm_mu:.2f} and $\sigma=$ {norm_sigma:.2f} )' # 关键步骤:提取拟合曲线的句柄(distplot返回的元组中第一个是拟合线) fit_line = normal_plot.get_lines()[0] # 明确指定句柄和标签 ax[0].legend(handles=[fit_line], labels=[norm_legend]) # 第二个子图示例(比如对数转换后的分布) log_target = np.log(target) log_plot = sns.distplot(log_target, ax=ax[1]) ax[1].set_title('Log-Transformed SalePrice Distribution') log_mu, log_sigma = norm.fit(log_target) log_legend = f'Normal dist. ($\mu=$ {log_mu:.2f} and $\sigma=$ {log_sigma:.2f} )' log_fit_line = log_plot.get_lines()[0] ax[1].legend(handles=[log_fit_line], labels=[log_legend]) plt.tight_layout() plt.show()
更推荐的替代方案(seaborn新版本用法)
现在seaborn已经不推荐使用distplot了,官方建议用histplot(画直方图)+kdeplot(画密度曲线),或者直接用histplot的kde=True参数同时绘制,这种方式的元素更易控制:
# 用histplot替代distplot sns.histplot(target, kde=True, ax=ax[0]) ax[0].set_title('Normal SalePrice Distribution') norm_mu, norm_sigma = norm.fit(target) norm_legend = f'Normal dist. ($\mu=$ {norm_mu:.2f} and $\sigma=$ {norm_sigma:.2f} )' # 直接从轴对象获取kde曲线的句柄 kde_line = ax[0].lines[0] ax[0].legend(handles=[kde_line], labels=[norm_legend])
这样代码更清晰,也不容易出现图例识别错误的问题。
内容的提问来源于stack exchange,提问作者pablora
相关产品推荐
相关产品推荐

