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

Python直方图柱子未居中:3上方柱子偏移问题求助

解决直方图柱子偏移的问题

这个问题不是bug,而是pandas默认分箱逻辑导致的~ 咱们来拆解一下原因和解决办法:

问题根源

pandas的hist()方法默认会自动计算分箱数量(默认是10个),当你的数据是1-5的整数时,自动生成的分箱边界不会刚好和整数刻度对齐。比如默认分箱可能是[0.9, 1.8, 2.7, 3.6, 4.5, 5.4]这类,这时候即使设置了align='mid',柱子的中点也不会落在你设置的xticks([1,2,3,4,5])上,看起来就像偏移了。

解决方案:手动指定分箱边界

你需要手动设置分箱,让每个整数对应一个独立的分箱,确保柱子的中点刚好对齐整数刻度。修改后的代码如下:

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

# 设置seaborn-whitegrid样式
plt.style.use('seaborn-whitegrid')

def createBarChart(colName):
    # 手动指定分箱:0.5到6.5,步长1,每个整数对应一个分箱区间
    bins = np.arange(0.5, 6.5, 1)
    df[colName].hist(align='mid', bins=bins)
    plt.title(str(colName))
    RUNS = [1,2,3,4,5]
    plt.xticks(RUNS)
    plt.show()

# 重建数据
df = pd.DataFrame(np.random.randint(1,6,size=(100, 4)), columns=list('ABCD'))
colName = df.columns.tolist()

for column in colName:
    createBarChart(column)

为什么这样有效?

np.arange(0.5, 6.5, 1)生成的分箱边界是[0.5,1.5,2.5,3.5,4.5,5.5],每个柱子对应的区间是:

  • 0.5-1.5 → 对应x轴1的位置
  • 1.5-2.5 → 对应x轴2的位置
  • ...以此类推

加上align='mid',每个柱子的中点正好落在1、2、3、4、5这些刻度上,就不会出现偏移了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:58:50