【发布时间】:2019-01-30 17:02:08
【问题描述】:
这是我的堆积条形图代码。我可以为第一个段 (AA) 添加百分比值,但是如何为所有 4 个段添加值?
df = pd.read_csv("123.csv")
df1 = df.groupby(['Country', 'ClassWeight'])
['Count'].sum().unstack('ClassWeight').fillna(0)
#sort on the 'total' column, and then drop it to avoid double plotting
ax = df1.sort_values(['total']).iloc[:,:-1].plot(kind='barh', width=0.8,
stacked=True, figsize=(15, 10),colormap=ListedColormap(sns.color_palette("Blues_d")))
#plot barchart
ax.set_xlabel('No.of Shipments',fontsize=15)
ax.set_ylabel('Country',fontsize=15)
plt.xticks(fontsize=15)
plt.yticks(fontsize=15)
plt.title('Total Shipments by Country and Customer Class',fontsize=15)
df2=df1.sort_values(['total'],ascending=True)
df2['AA'] = 100*df2['AA']/df2['total']
df2['A'] = 100*df2['A']/df2['total']
df2['B'] = 100*df2['B']/df2['total']
df2['C'] = 100*df2['C']/df2['total']
df3 = df2.iloc[:,:-1]
#Can only enumerate on the AA column. How could we do all 4 columns?
for i, v in enumerate(df3['AA']):
ax.text(v + -1, i + -0.2, str("{0:.1f}%".format(v)), color='white',
fontweight='bold', fontsize=15)
示例数据:
ClassWeight AA A B C
Country
Romania 17.142857 32.268908 28.235294 22.352941
Finland 60.325203 13.495935 12.682927 13.495935
{'Country': {0: 'France', 1: 'Poland', 2: 'Lithuania', 3: 'United Kingdom', 4: 'Denmark'}, 'Count': {0: 233, 1: 232, 2: 286, 3: 236, 4: 223}, 'SumWeight': {0: 8072469.5, 1: 6689511.05, 2: 5158305.25, 3: 4675914.53, 4: 3536684.52}, 'AvgWeight': {0: 34645.79, 1: 28834.1, 2: 18036.03, 3: 19813.2, 4: 15859.57}, 'ClassWeight': {0: 'AA', 1: 'AA', 2: 'AA', 3: 'AA', 4: 'AA'}}
【问题讨论】:
-
您可以将您的一些示例数据作为文本而不是图像编辑到您的帖子中吗?它使人们更容易使用。
-
感谢编辑
-
您的示例数据代表哪个框架?
标签: python pandas matplotlib charts enumerate