我有一个子图条形图,编码为:
axes = df.plot.bar(yerr=df1, figsize=(10,8), legend=False,
title='Bar chart',grid=1, subplots=True, layout (5,1),xticks=None)
是否有一种简单的方法来修改代码,以便查看每个栏顶部数据框df中的数值?
更新:下面的代码仍然没有值:
df = DataFrame(np.zeros((5, 3)))
df.index=['[1,3)','[3, 4)','[4, 5)','[5, 6)','[7]']
df.columns=['cat1','cat2','cat3']
df.iloc[0,:]= np.array( [0.4, 0.3, 0.2])
df.iloc[1,:]= np.array( [0, 0.1, 0.9])
df.iloc[2,:]= np.array( [0.3, 0.1, 0.3])
df.iloc[3,:]= np.array( [0, 0, 0.2])
df.iloc[4,:]= np.array( [0.0, 0, 0.9])
se_df = DataFrame(np.zeros((5, 3)))
se_df.index=['[1,3)','[3, 4)','[4, 5)','[5, 6)','[7]']
se_df.columns=['cat1','cat2','cat3']
se_df.iloc[0,:]= np.array( [0.1, 0.2, 0.002])
se_df.iloc[1,:]= np.array( [0.003, 0.02, 0.008])
se_df.iloc[2,:]= np.array( [0.006, 0.03, 0.0002])
se_df.iloc[3,:]= np.array( [0.001, 0, 0.0001])
se_df.iloc[4,:]= np.array( [0.0001, 0, 0.0002])
df1=df.transpose()
se_df1=se_df.transpose()
axes = df1.plot.bar(yerr=se_df1, figsize=(10,8), legend=False,
title='Title',grid=1, subplots=True, layout=(5,1),xticks=None)
for n,i in enumerate(axes, 1):
for rec, label in zip(i.patches,df.loc[:, n].astype(str)):
height = rec.get_height()
i.text(rec.get_x() + rec.get_width() / 2, height - 5, label,
ha = 'center', va='bottom', color='w', weight='bold')
plt.tight_layout()
您能指出我在做什么错吗?
答案 0 :(得分:2)
使用您的新代码更新:
df = pd.DataFrame(np.zeros((5, 3)))
df.index=['[1,3)','[3, 4)','[4, 5)','[5, 6)','[7]']
df.columns=['cat1','cat2','cat3']
df.iloc[0,:]= np.array( [0.4, 0.3, 0.2])
df.iloc[1,:]= np.array( [0, 0.1, 0.9])
df.iloc[2,:]= np.array( [0.3, 0.1, 0.3])
df.iloc[3,:]= np.array( [0, 0, 0.2])
df.iloc[4,:]= np.array( [0.0, 0, 0.9])
se_df = pd.DataFrame(np.zeros((5, 3)))
se_df.index=['[1,3)','[3, 4)','[4, 5)','[5, 6)','[7]']
se_df.columns=['cat1','cat2','cat3']
se_df.iloc[0,:]= np.array( [0.1, 0.2, 0.002])
se_df.iloc[1,:]= np.array( [0.003, 0.02, 0.008])
se_df.iloc[2,:]= np.array( [0.006, 0.03, 0.0002])
se_df.iloc[3,:]= np.array( [0.001, 0, 0.0001])
se_df.iloc[4,:]= np.array( [0.0001, 0, 0.0002])
df1=df.transpose()
se_df1=se_df.transpose()
naxes = df1.plot.bar(yerr=se_df1, figsize=(10,8), legend=False,
title='Title',grid=1, subplots=True, layout=(5,1),xticks=None)
for n,i in enumerate(naxes, 1):
for rec, label in zip(i[0].patches,df1.iloc[:, n-1].astype(str)):
height = rec.get_height()
i[0].text(rec.get_x() + rec.get_width() / 2, height * .8, label,
ha = 'center', va='bottom', color='w', weight='bold')
plt.tight_layout()
让我们使用:
np.random.seed(20)
df = pd.DataFrame({'Chart':[1,2,3,4]*3,'x':[1,2,3]*4,'y':np.random.randint(0,50,12)})
df_chart = df.set_index(['x','Chart'])['y'].unstack()
naxes = df_chart.plot.bar(subplots=True, figsize=(15,10), grid=1, yerr=df.groupby(['Chart'])['y'].transform('std'))
for n,i in enumerate(naxes, 1):
for rec, label in zip(i.patches,df_chart.loc[:, n].astype(str)):
height = rec.get_height()
i.text(rec.get_x() + rec.get_width() / 2, height - 5, label,
ha = 'center', va='bottom', color='w', weight='bold')
plt.tight_layout()
输出: