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

如何解决matplotlib绘图时x轴分类标签自动去重压缩的问题?

解决方法

matplotlib默认会将字符串类型的x坐标识别为分类变量,相同值会自动合并去重,要保留原始标签的重复值和顺序,用「数值索引占位+手动替换标签」的方式即可实现,无需修改底层配置。

核心实现步骤

  • 先用和标签列表长度一致的整数序列作为x坐标绘图,避免触发分类去重逻辑
  • 手动将x轴刻度的标签替换为原始的字符串列表

基础代码示例

import matplotlib.pyplot as plt

# 你的原始数据
list1 = ['A1', 'A2', 'A1', 'A3']
y_data = [1, 3, 2, 4] # 替换为你自己的y轴数值

# 生成占位用的x轴索引
x_index = range(len(list1))

# 绘图时用索引作为x坐标,支持所有绘图类型:plot/scatter/bar等都通用
plt.bar(x_index, y_data)

# 手动设置刻度和对应标签
plt.xticks(ticks=x_index, labels=list1)

# 可选:如果标签过长重叠,可加旋转参数
# plt.xticks(ticks=x_index, labels=list1, rotation=30)

plt.show()

子图(Axes对象)用法

如果是面向对象的子图写法,调整为对应接口即可:

import matplotlib.pyplot as plt

list1 = ['A1', 'A2', 'A1', 'A3']
y_data = [1, 3, 2, 4]
x_index = range(len(list1))

fig, ax = plt.subplots()
ax.plot(x_index, y_data)
ax.set_xticks(x_index)
ax.set_xticklabels(list1)

plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 11:39:01