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

使用Pandas绘制堆叠柱状图时无法设置整数间隔X轴刻度的问题

问题:Pandas堆叠柱状图设置整数间隔X轴刻度失败

我使用Pandas DataFrame的plot方法绘制堆叠柱状图,X轴的值为浮点数,想要将X轴刻度设置为整数间隔,但尝试后并未成功。

我的代码

import pandas as pd
import numpy as np
from matplotlib import pyplot as plt

data = [[0.0, 4.9, 19.9, 8.1, 0.0], [0.12, 4.5, 27.0, 10.1, 0.0], 
        [0.24, 2.8, 9.3, 4.6, 0.0], [0.36, 2.2, 9.1, 2.7, 0.0], 
        [0.48, 2.2, 7.3, 3.1, 0.0], [1.0, 4.9, 26.4, 11.2, 0.0], 
        [1.12, 5.9, 25.3, 8.7, 0.0], [1.24, 3.7, 13.3, 7.1, 0.0], 
        [1.3599999999999999, 3.0, 9.5, 3.4, 0.0], [1.48, 3.2, 8.9, 4.7, 0.0], 
        [2.0, 8.4, 24.8, 20.2, 0.0], [2.12, 9.5, 19.3, 22.5, 0.0], 
        [2.24, 5.7, 11.8, 6.6, 0.0], [2.36, 4.1, 11.1, 5.1, 0.0], 
        [2.48, 5.4, 8.0, 4.6, 0.0]]
df = pd.DataFrame(columns = ['xval', 'y1', 'y2', 'y3', 'y4'], data = data)
fig, ax = plt.subplots()
df.plot(x = 'xval', kind = 'bar', ax = ax, stacked = True)
xticks = [x for x in df['xval'] if int(x) == x]
ticklabel = ['{:.1f}'.format(x) for x in xticks]
ax.set_xticks(xticks, labels = ticklabel)
ax.grid()
fig.savefig('mychart.png')

当前效果

图表效果截图

解决方法

问题核心:Pandas绘制柱状图时,X轴刻度位置对应的是DataFrame的索引,而非xval列的数值。直接用xval的数值设置刻度位置,和matplotlib的坐标体系不匹配,导致设置无效。

修正后的代码:

import pandas as pd
import numpy as np
from matplotlib import pyplot as plt

data = [[0.0, 4.9, 19.9, 8.1, 0.0], [0.12, 4.5, 27.0, 10.1, 0.0], 
        [0.24, 2.8, 9.3, 4.6, 0.0], [0.36, 2.2, 9.1, 2.7, 0.0], 
        [0.48, 2.2, 7.3, 3.1, 0.0], [1.0, 4.9, 26.4, 11.2, 0.0], 
        [1.12, 5.9, 25.3, 8.7, 0.0], [1.24, 3.7, 13.3, 7.1, 0.0], 
        [1.3599999999999999, 3.0, 9.5, 3.4, 0.0], [1.48, 3.2, 8.9, 4.7, 0.0], 
        [2.0, 8.4, 24.8, 20.2, 0.0], [2.12, 9.5, 19.3, 22.5, 0.0], 
        [2.24, 5.7, 11.8, 6.6, 0.0], [2.36, 4.1, 11.1, 5.1, 0.0], 
        [2.48, 5.4, 8.0, 4.6, 0.0]]
df = pd.DataFrame(columns = ['xval', 'y1', 'y2', 'y3', 'y4'], data = data)
fig, ax = plt.subplots()
df.plot(x = 'xval', kind = 'bar', ax = ax, stacked = True)

# 找到xval为整数的行对应的索引位置
xtick_indices = df[df['xval'].apply(lambda x: int(x) == x)].index
# 生成对应刻度标签
tick_labels = ['{:.1f}'.format(x) for x in df.loc[xtick_indices, 'xval']]
# 基于索引设置刻度位置和标签
ax.set_xticks(xtick_indices, labels=tick_labels)

ax.grid()
fig.savefig('mychart.png')

修改后,X轴会只显示整数间隔的刻度,且对应到正确的柱状图位置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 15:09:55