You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Seaborn kdeplot自动设置y轴标签为Density自定义行标签不显示如何修复

问题修复方案

以下是可直接运行的修复后代码:

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
sns.set_style("darkgrid")

s1, s2 = 5, 3
# 调整子图右侧边距,预留位置放右侧行标签
fig, axes = plt.subplots(s1, s2, figsize=(4*5, 5*5), sharey=True, 
                         gridspec_kw={'right': 0.9})
fig.suptitle(t="Suptitle", x=0.5, y=1-0.075, fontsize=40)
for ind1 in range(s1):
    for ind2 in range(s2):
        data=np.random.normal(size=100)
        sns.kdeplot(data, ax=axes[ind1, ind2], bw_adjust=1, 
                    linewidth=0.9, color="C9", alpha=0.5)
        # 清空每个子图自动生成的左侧y轴"Density"标签
        axes[ind1, ind2].set_ylabel("")
for ax, col in zip(axes[0], ["column_%d" %i for i in range(s2)]):
    ax.set_title(col, size=25)
for ax, row in zip(axes[:,-1], ["row_%d" %i for i in range(s1)]):
    ax.yaxis.set_label_position("right")
    # 显式将最后一列子图的y轴刻度也移动到右侧,避免标签被共享轴配置覆盖
    ax.yaxis.tick_right()
    ax.set_ylabel(row, rotation=90, size=25)

fig.text(0.5, 0.075, 'Common x label', ha='center', size = 30)
fig.text(0.065, 0.5, 'Common y label', va='center', rotation='vertical', size = 30)
# 调整全局布局,避免各类标签、标题被裁切
plt.tight_layout(rect=[0.07, 0.08, 0.9, 0.92])
plt.show()

原代码问题原因

  1. seaborn的kdeplot默认会为每个子图的y轴添加Density标签,占用了左侧y轴位置,遮挡全局公共标签
  2. 默认子图布局的右侧边距过小,自定义的右侧行标签超出画布可视范围,因此无法正常显示
  3. 仅设置了标签位置为右侧,没有同步调整刻度位置,子图共享y轴的全局配置会覆盖单轴的标签显示设置

关键修改点说明

  • 创建子图时通过gridspec_kw={'right': 0.9}将子图区域右边界限定在画布90%宽度位置,剩余空间用来显示右侧自定义行标签
  • 每次绘制完kdeplot后显式清空自动生成的y轴标签,保留左侧空白位置给全局公共y轴标签
  • 显式将最后一列子图的y轴刻度移动到右侧,配合标签位置设置,保证自定义行标签正常渲染
  • 通过tight_layout的rect参数限定子图布局的上下左右边界,避免公共x/y轴标签、全局总标题被裁切

内容的提问来源于stack exchange,提问作者1 1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 21:45:05