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

如何移除Seaborn图表左侧坐标轴的标签?

解决左侧坐标轴"Dogs"标签无法移除的问题

你的问题核心在于调用seaborn.barplot时没有指定使用预先创建的ax对象,每次设置ax=None都会生成新的坐标轴,导致你后续对ax的移除标签、刻度等操作,完全没作用到实际绘图的轴上。

修复步骤:

  1. 将所有sns.barplot中的ax=None替换为ax=ax,让所有条形图都绘制在同一个坐标轴上
  2. 保留后续移除标签、刻度的代码即可生效

修改后的完整代码:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

df = pd.DataFrame({
    'index': ['Dogs', 'Birds', 'Cats'],
    'percent': [20.444444, 53.629630, 100.000000],
})

# 拆分DataFrame的操作可以保留,不影响核心修复
df_1 = df.iloc[[0]]
df_2 = df.iloc[[1]]
df_3 = df.iloc[[2]]

sns.set_theme(style="whitegrid")

# 创建唯一的坐标轴对象
f, ax = plt.subplots(figsize=(30, 10))

# 关键:指定ax=ax,所有绘图共用同一个坐标轴
sns.barplot(x="percent", y="index", data=df_3, color='#d7301f', ax=ax)
sns.barplot(x="percent", y="index", data=df_2, color='#fc8d59', ax=ax)
sns.barplot(x="percent", y="index", data=df_1, color='#fdcc8a', ax=ax)

# 添加文本注释
ax.text(0.1, 0.5, "Dogs (20%)", ha="center", va="center", transform=ax.transAxes, color='#313639', fontsize=30)
ax.text(0.35, 0.5, "Birds (33%)", ha="center", va="center", transform=ax.transAxes, color='#313639', fontsize=30)
ax.text(0.76, 0.5, "Cats (46%)", ha="center", va="center", transform=ax.transAxes, color='#313639', fontsize=30)

# 移除刻度和标签
ax.set(xticklabels=[], xlabel=None, ylabel=None)
sns.despine(bottom=True, left=True)
ax.grid(False)

plt.show()  # 建议加上这行确保图表正常显示

额外优化建议:

你可以不用拆分DataFrame,直接循环绘制,代码更简洁:

# 替换拆分和三次barplot的代码
colors = ['#fdcc8a', '#fc8d59', '#d7301f']
for idx, row in df.iterrows():
    sns.barplot(x=[row['percent']], y=[row['index']], color=colors[idx], ax=ax)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 00:13:34