繁体   English   中英

将条形图文本格式化为 2 个小数位

[英]Format bar chart text to 2 decimal places

我的工作代码如下:

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()

它产生这个输出:

              Total Parking Spaces  % of Total
Owned/Leased                                  
LEASED                   44.707349   37.546059
OWNED                    74.365997   62.453941 

但是我的情节有两个我似乎无法解决的问题:

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?

在此处输入图片说明

即使我使用以下内容裁剪文本显示:pd.options.display.float_format = '{:.2f}'.format,该图仍显示 14 位小数。

用:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM