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

pandas分组柱状图最后一根条被遮挡,如何在不缩小柱宽时解决?

解决方案

你遇到的最后一组红色柱被截断的问题,本质是pandas绘制柱状图时默认的X轴范围没有为并排的两个柱子预留足够的右侧空间,以下是两种满足你需求的可行方案:

方案1:仅调整X轴范围(无需修改柱宽、无需调整组间距)

只需要在绘图代码末尾增加一行X轴范围设置即可解决截断问题,原有柱宽、组间距都不需要改动:

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

df = pd.DataFrame({'x':[0.716468, 0.799652, 0.611284, 0.700020, 0.745372, 0.717280, 0.212407, 0.225291, 0.443395, 0.649912, 0.756463, 0.588992],
'y':[1.891988, 2.750937, 4.495497, 5.260436, 6.100882, 6.262784, 7.339279, 6.877465, 6.349050, 4.797649, 3.290293, 2.106541],
'x_err':[0.022882, 0.021447, 0.009402, 0.011324, 0.008872, 0.015882, 0.009615, 0.007617, 0.012816, 0.010310, 0.009213, 0.020137],
'y_err':[0.156298, 0.151681, 0.178215, 0.143700, 0.137071, 0.133951, 0.209588, 0.185246, 0.214665, 0.214598, 0.163624, 0.132138]})

fig, ax = plt.subplots()
width = 0.35
df['x'].plot(kind = 'bar',ax = ax ,width = width, position = 0 , yerr = df['x_err'],color = 'red',use_index = True)
ax.set_ylabel('X')

ax1= ax.twinx()
df['y'].plot(kind = 'bar',ax = ax1 ,width = width, position = 1 , yerr = df['y_err'],color = 'blue',use_index = True)
ax1.set_ylabel('Y')

# 新增这行调整X轴范围,预留足够的右侧空间
ax.set_xlim(-0.5, len(df) - 1 + 0.4)

plt.show()

方案2:缩小组间空隙+自定义柱子位置(适配你希望压缩组间空白的需求)

直接用matplotlib原生的bar方法绘制,自定义每组的X坐标,缩小分组之间的间隔,既可以保持你需要的柱宽,又能让所有柱子完整显示:

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

df = pd.DataFrame({'x':[0.716468, 0.799652, 0.611284, 0.700020, 0.745372, 0.717280, 0.212407, 0.225291, 0.443395, 0.649912, 0.756463, 0.588992],
'y':[1.891988, 2.750937, 4.495497, 5.260436, 6.100882, 6.262784, 7.339279, 6.877465, 6.349050, 4.797649, 3.290293, 2.106541],
'x_err':[0.022882, 0.021447, 0.009402, 0.011324, 0.008872, 0.015882, 0.009615, 0.007617, 0.012816, 0.010310, 0.009213, 0.020137],
'y_err':[0.156298, 0.151681, 0.178215, 0.143700, 0.137071, 0.133951, 0.209588, 0.185246, 0.214665, 0.214598, 0.163624, 0.132138]})

fig, ax = plt.subplots()
width = 0.35
# 自定义组间距,可自行调整数值缩小/增大组间空白
group_gap = 0.2
x = np.arange(len(df)) * (width * 2 + group_gap)

# 绘制第一组柱
ax.bar(x - width/2, df['x'], width=width, yerr=df['x_err'], color='red')
ax.set_ylabel('X')
ax.set_xticks(x)
ax.set_xticklabels(df.index)

# 绘制第二组柱
ax1 = ax.twinx()
ax1.bar(x + width/2, df['y'], width=width, yerr=df['y_err'], color='blue')
ax1.set_ylabel('Y')

plt.show()

你可以通过调整group_gap的数值来控制分组之间的空隙大小,数值越小组间越紧凑。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 21:06:05