Pandas中的奇怪条形图对齐问题
我在用pandas生成一个柱状图,使用的命令如下(这里的x是一个已经存在的数据框):
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版本,还有没有简单的解决办法呢?
1 个回答
1
这可能和matplotlib中的这个bug有关,影响了一些版本低于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()