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

Matplotlib堆叠柱状图X轴标签仅间隔显示无法全部展示问题求助

Matplotlib X轴标签仅间隔显示的解决方案

你遇到的X轴标签只显示每隔一个的问题,主要由两个错误用法导致:

  1. set_xticks方法误用:Matplotlib的set_xticks仅接收刻度位置参数,你额外传入的labels参数在多数版本中不会生效,反而会干扰刻度映射逻辑
  2. 画布边距不足:你用ax = fig.add_axes([0,0,1,1])让绘图区域完全占满画布,旋转90度的X轴标签没有足够的底部空间显示,Matplotlib会自动隐藏重叠的标签避免内容溢出

方案1:改用标准画布创建方式(推荐)

修改后的完整代码如下:

import numpy as np
import matplotlib.pyplot as plt

m_count=  [12, 12, 13, 16, 12, 12, 13, 16, 9, 10]
f_count =[13, 13, 12, 9, 13, 13, 11, 9, 15, 15]
    
labels = ["Capomulin", "Ceftamin", "Infubinol", "Ketapril", "Naftisol", "Placebo", "Propriva", "Ramicane", "Stelasyn", "Zoniferol"]
N=10
ind = np.arange(N)
width = .35
# 改用subplots创建带默认边距的画布
fig, ax = plt.subplots()
ax.bar(ind, m_count, width, color ="b")
ax.bar(ind, f_count, width, color ="r", bottom=m_count)
ax.set_ylabel('Count')
ax.set_title("Count of Mice by Drug Regimen")
# set_xticks仅传入刻度位置即可
ax.set_xticks(ind)
ax.set_xticklabels(labels, rotation=90 )
ax.set_yticks(np.arange(0, 30, 2))
ax.legend(labels=['Male', 'Female'])
# 自动调整边距避免标签被截断
fig.tight_layout()
plt.show()

方案2:保留add_axes写法调整边距

如果你需要自定义绘图区域的位置,只需要调整add_axes的参数,预留底部空间即可:
把原代码里的
ax = fig.add_axes([0,0,1,1])
替换为
ax = fig.add_axes([0.1, 0.2, 0.8, 0.7])
四个参数分别对应「左边界距离、下边界距离、宽度、高度」,这里下边界留20%的画布高度放旋转后的X轴标签,就能正常显示所有标签。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 10:48:03