[英]Format bar chart text to 2 decimal places
I have working code as follows:我的工作代码如下:
active_parking = pd.pivot_table(parking[parking['Bldg Status'] == 'ACTIVE'],
index='Owned/Leased',
values='Total Parking Spaces',
aggfunc='mean'
)
active_parking['% of Total'] = ((active_parking['Total Parking Spaces'] / active_parking['Total Parking Spaces'].sum()) * 100)
print(active_parking, '\n')
active_parking.plot(kind='bar')
for i, number in enumerate(active_parking['Total Parking Spaces']):
plt.text(x=i, y=number, s=number, horizontalalignment='center', weight='bold')
for i, number in enumerate(active_parking['% of Total']):
plt.text(x=i, y=number, s=number, horizontalalignment='left', weight='bold')
plt.xticks(rotation=0)
plt.show()
And it produces this output:它产生这个输出:
Total Parking Spaces % of Total
Owned/Leased
LEASED 44.707349 37.546059
OWNED 74.365997 62.453941
But my plot has two issues that I can't seem to solve:但是我的情节有两个我似乎无法解决的问题:
1) I want the displayed value on top of each bar limited to two decimal places.
2) After solving the above issue, how do I center the value over each bar?
Even if I crop the text display with this: pd.options.display.float_format = '{:.2f}'.format, the plot still shows 14 decimal places.即使我使用以下内容裁剪文本显示:pd.options.display.float_format = '{:.2f}'.format,该图仍显示 14 位小数。
Use:用:
active_parking.plot(kind='bar')
for i, number in enumerate(active_parking['Total Parking Spaces']):
plt.text(x=i-.23, y=number + 0.9, s=round(number, 2), weight='bold')
for i, number in enumerate(active_parking['% of Total']):
plt.text(x=i+.02, y=number + 0.9, s=round(number, 2), weight='bold')
plt.xticks(rotation=0)
plt.ylim(top=active_parking.values.max() + 8)
plt.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.