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

如何调整Pandas的plot.hist()实现直方图更优展示

修复方案

问题根因

  • plot.hist() 默认会自动计算分箱范围,你的第一行数据只有3、7两个唯一值,默认生成的两个分箱区间是[3,5)、[5,7],导致两个柱子的中心分别落在4、6位置,和预期的3、7错位。
  • 默认x轴刻度会根据分箱范围自动生成浮点数格式,不符合整数显示要求。

修复代码

方案1:调整直方图参数实现需求

import matplotlib.pyplot as plt

row = df.iloc[0].astype(int)
# 手动指定分箱边界,边界落在整数中间,让每个整数对应bin的中心
plt.hist(row, bins=[i - 0.5 for i in range(2, 9)], edgecolor='black')
# 强制x轴显示3到7的整数刻度
plt.xticks(range(3, 8))
plt.show()

方案2:离散值用柱状图更适配

你的数据是离散整数取值,用柱状图逻辑更简单,不需要调整分箱:

import matplotlib.pyplot as plt

row = df.iloc[0].astype(int)
# 统计每个值的出现次数后绘图
row.value_counts().sort_index().plot(kind='bar')
# 取消x轴刻度旋转
plt.xticks(rotation=0)
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 00:36:02