首页 > 解决方案 > 如何在 Python 中更改水平条形图上标签的格式?

问题描述

我需要使用分隔英里和数百万的点来更改标签中的格式。例如,我有 10327423,我需要这种格式:10.327.423

我有一个名为“df”的数据框,其中包含每个国家/地区的国家(西班牙语中的 Paises)和感染人数(西班牙语中的 Contagiados)。像这样: 点击查看

我的代码是:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
Row_list =[] 
for index, rows in df.iterrows(): 
     my_list =rows.Contagiados 
     Row_list.append(my_list) 
# Print the list 
print(Row_list) 
my_array = np.array(Row_list)
# printing my_array
print (my_array)
#
fig, ax = plt.subplots()
bar_horizontal = ax.barh(df.Paises, df.Contagiados, align='center', alpha=0.5)
plt.xlabel('Contagiados')
plt.title('Contagiados por País')
plt.rcParams['figure.figsize'] = 10, 15

for index, value in enumerate(my_array):
    plt.text(value, index, str(value))
plt.show()

结果

标签: pythonpandasmatplotlib

解决方案


您可以这样做以另一种方式格式化数字。作为 '。' 不常用于数字分隔符,您可以设置 ',' 并使用替换

plt.text(value, index, str('{:,}'.format(value).replace(',','.')))

推荐阅读