Pandas 在注释中显示小数点
我有一个数据框,例如:Pandas 在注释中显示小数点,pandas,dataframe,Pandas,Dataframe,我有一个数据框,例如: pt car walk bike EO 19221 15442 12932 1489 EW 19025 15484 12979 1494 Inc 21568 13650 12590 1276 Inc2 21705 13499 12608 1272 我想有一个百分比的整体价值观,并显示在一个条形图。 我编写了以下代码: Colors_list = ['#5cb85c','#5bc0de','
pt car walk bike
EO 19221 15442 12932 1489
EW 19025 15484 12979 1494
Inc 21568 13650 12590 1276
Inc2 21705 13499 12608 1272
我想有一个百分比的整体价值观,并显示在一个条形图。
我编写了以下代码:
Colors_list = ['#5cb85c','#5bc0de','#d9534f']
# Change this line to plot percentages instead of absolute values
ax = (df.div(df.sum(1), axis=0)).plot(kind='bar',
stacked = True, figsize=(10,6),width = 0.4,edgecolor=None)
plt.legend(labels=df.columns,fontsize= 14)
plt.legend(loc='best')
plt.xticks(rotation=0, horizontalalignment="center")
plt.xticks(fontsize=14)
for spine in plt.gca().spines.values():
spine.set_visible(True)
plt.yticks(fontsize=14)
# Add this loop to add the annotations
for p in ax.patches:
width, height = p.get_width(), p.get_height()
x, y = p.get_xy()
ax.annotate('{:.0%}'.format(height), (x + 0.05, y + 0.01), fontsize=14)
它很好用。唯一的问题是它显示的百分比没有任何小数点。
例如,它显示为:
26% 26% 26% 26%
但是,我需要:
26.35% 26.50% 25.65% 25.69%
使用
格式中的.2
表示两位小数:
ax.annotate('{:.2%}'.format(height), (x + 0.05, y + 0.01), fontsize=14)
使用格式中的.2
表示两位小数:
ax.annotate('{:.2%}'.format(height), (x + 0.05, y + 0.01), fontsize=14)