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

使用Seaborn绘制柱状图时Y轴刻度不显示,如何解决?

解决Seaborn柱状图Y轴刻度不显示的问题

问题根源在你代码的最后部分:

plt.setp(f.axes, yticks=[])

这行代码会遍历所有子图的坐标轴,强制将Y轴刻度设置为空列表,直接覆盖了你之前为每个子图单独配置的set_yticks,导致刻度无法显示。

修正方案

删除或注释掉这行代码即可恢复Y轴刻度。修正后的完整代码如下:

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_theme(style="white", context="talk")
rs = np.random.RandomState(8)

# Set up the matplotlib figure
f, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(7, 5), sharex=True)

# Generate some sequential data
x = np.array(list("ABCDEFGHIJ"))
y1 = np.arange(1, 11)
sns.barplot(x=x, y=y1, palette="rocket", ax=ax1)
ax1.axhline(0, color="k", clip_on=False)
ax1.set_yticks(y1)
ax1.set_ylabel("Sequential")

# Center the data to make it diverging
y2 = y1 - 5.5
sns.barplot(x=x, y=y2, palette="vlag", ax=ax2)
ax2.axhline(0, color="k", clip_on=False)
ax2.set_yticks(y2)
ax2.set_ylabel("Diverging")

# Randomly reorder the data to make it qualitative
y3 = rs.choice(y1, len(y1), replace=False)
sns.barplot(x=x, y=y3, palette="deep", ax=ax3)
ax3.axhline(0, color="k", clip_on=False)
ax3.set_yticks(y3)
ax3.set_ylabel("Qualitative")

# Finalize the plot
sns.despine(bottom=True)
# plt.setp(f.axes, yticks=[])  # 注释或删除此行
plt.tight_layout(h_pad=2)
plt.show()  # 添加此行确保图形正常显示

补充说明

如果原本想用plt.setp做其他坐标轴配置,注意不要包含yticks=[]参数,避免再次覆盖刻度设置。你之前为每个子图调用的set_yticks是有效的,只要不被后续代码修改,就能正常显示自定义刻度。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 23:02:12