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

Matplotlib中X轴刻度不显示问题求助(Python3.6+macOS)

解决Matplotlib显示字典键为X轴刻度的问题

嘿,我看到你在macOS+Python3.6环境下用Matplotlib绘制字典数据时,遇到了X轴刻度没显示成字典键的问题,咱们来快速搞定它!

问题根源

你的代码里有个明显的小疏漏:在plt.xticks()函数中,你把第二个参数(刻度标签)写成了list(D.values()),但你实际想要显示的是字典的键list(D.keys())。这就导致X轴显示的是字典的值,而非你期望的键。

另外还有个小细节:你设置的figsize=(500,100)实在太大了,这会让图表显示异常,建议改成更合理的数值,比如(15,8)。

修正后的完整代码

import pandas as pd
import glob
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
%matplotlib inline

# 替换成你实际的info_dict数据
info_dict = {"类别1": 23, "类别2": 45, "类别3": 18, "类别4": 32}
D = info_dict

# 调整画布尺寸为合理范围
figure(num=None, figsize=(15, 8), dpi=80, facecolor='w', edgecolor='k')

x = list(D.keys())
y = list(D.values())

plt.bar(x, y)
# 关键修正:把刻度标签改成字典的键
plt.xticks(range(len(D)), list(D.keys()), rotation='vertical')
plt.margins(0.2)
plt.subplots_adjust(bottom=0.15)
plt.show()

更简洁的写法

其实当你用plt.bar(x, y)时,x已经是字典键的列表,Matplotlib默认会把这些键作为X轴刻度,所以你甚至可以省略手动指定刻度位置的步骤,直接设置旋转即可:

import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
%matplotlib inline

info_dict = {"类别1": 23, "类别2": 45, "类别3": 18, "类别4": 32}
D = info_dict

figure(num=None, figsize=(15, 8), dpi=80, facecolor='w', edgecolor='k')

x = list(D.keys())
y = list(D.values())

plt.bar(x, y)
# 直接设置刻度旋转,自动使用x中的键作为刻度
plt.xticks(rotation='vertical')
plt.margins(0.2)
plt.subplots_adjust(bottom=0.15)
plt.show()

这样修改后,X轴就会正确显示字典的键作为刻度啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 09:10:43