Skip to main content
 首页 » 编程设计

python之Pandas 中奇怪的条形图对齐

2025年05月04日13tuyile006

我正在使用以下命令在 pandas 中生成条形图(其中 x 是现有的 DataFrame):

df = x.groupby(['pAlt']).describe()['win_stay'].unstack() 
df['se'] = df['std']/np.sqrt(df['count']) # calculate standard error 
df['mean'].plot(kind='bar',yerr=df.se,alpha=0.5,ax=ax,legend=False) 

除条形图的位置外,该图大体上看起来是正确的:

出于某种原因,它们紧靠绘图的右边缘,而不是居中。这似乎是 Pandas 0.14 中引入的一个新问题:如果我降级到 0.13.1 并运行完全相同的代码,情节如下所示:

除了坚持使用 pandas 的降级版本之外,还有其他简单的解决方法吗?

请您参考如下方法:

这可能与 this bug in matplotlib 有关,影响某些版本 < 1.4.0。 (我在 1.3.1 版本中看到了它)。

import pandas as pd 
import matplotlib.pyplot as plt 
import matplotlib as mpl 
 
print(pd.__version__) 
# 0.14.0 
print(mpl.__version__)     
# 1.3.1 
 
fig, ax = plt.subplots() 
df = pd.DataFrame({'mean': [0.25, 0.2, 0.25]}, index=[0.5, 0.8, 0.85]) 
df['mean'].plot(kind='bar', alpha=0.5, legend=False, ax=ax) 
 
ax.set_xlim(-1, len(df['mean'])) 
plt.show()