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

如何调整Pandas绘制直方图的X轴刻度为每1单位间隔显示

解决方案

核心逻辑:X轴刻度间隔由Matplotlib自动刻度规则控制,与bins分箱参数无关,手动指定刻度序列即可实现需求。同时建议调整分箱规则对齐整数,避免分箱跨整数导致统计结果不符合整数属性。

具体修改步骤

  • 调整分箱参数(可选但推荐):将bins设置为从1到最大length+2的整数序列,让每个分箱刚好对应一个整数值的统计区间
  • 手动指定X轴刻度:调用plt.xticks()传入步长为1的整数序列,强制每1单位显示一个刻度

修改后完整代码

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

# 此处df为你的原始数据框
max_len = df['length'].max()

plt.figure(figsize=(30,10))
# 调整bins对齐整数,每个分箱对应一个整数的统计
freq, bins, patches = plt.hist(df['length'],label='Number of ESL/Number of units', bins = range(1, max_len + 2), color=['#A0E8AF'])

bin_centers = np.diff(bins)*0.5 + bins[:-1]

n = 0
for fr, x, patch in zip(freq, bin_centers, patches):
    height = int(freq[n])
    plt.annotate("{}".format(height),
               xy = (x, height),             
               xytext = (0,0.1),             
               textcoords = "offset points",
               ha = 'center', va = 'bottom'
               )
    n = n+1

# 手动设置X轴刻度,每1单位显示一个
plt.xticks(range(1, max_len + 1))
plt.legend()
# 原代码遗漏了调用括号,此处补充
plt.show()

适配说明

如果你的length取值范围过大(超过50),每1单位显示刻度会出现标签重叠,可按需调整步长,例如每2单位显示一个刻度可修改为:
plt.xticks(range(1, max_len + 1, 2))


内容的提问来源于stack exchange,提问作者Serge de Gosson de Varennes

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 16:45:04