首页 > 解决方案 > 如何在条形图中显示百分比而不是值?

问题描述

有我下面的数据框和代码。

Gender    Actual    Predicted   new_salary
Female  47390.03    47344.005   48870.454
Male    49538.83    49584.995   49538.829

我的代码:

ax = df.plot(kind='bar',figsize=(15,8),width = 0.8,color = colors_list, edgecolor=None)

for p in ax.patches:
    width = p.get_width()
    height = p.get_height()
    x, y = p.get_xy() 
    ax.annotate(f'{height}', (x + width/2, y + height*1.02), ha='center')

我的代码的结果

目标new_salary:有没有办法显示与实际值和预测值相比增加了多少百分比?而不是值,我需要百分比变化。

标签: pythonpandasmatplotlibseaborn

解决方案


请检查代码段以显示百分比而不是值。刚刚将您的dataframe列转换为百分比格式。

columns = ['Actual','Predicted','new_salary']
df[columns] = df[columns].div(df[columns].sum(axis=1), axis=0).multiply(100).round({'Actual': 2, 'Predicted': 2,'new_salary': 2})

在此处输入图像描述

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
data = [['Female', 47390.03,47344.005,48870.454], ['male',49538.83,49584.995,49538.829]]
df = pd.DataFrame(data, columns = ['Gender', 'Actual','Predicted','new_salary']) 
colors_list=['green','blue','red']
posy=np.arange(len(df['Gender']))

columns = ['Actual','Predicted','new_salary']
df[columns] = df[columns].div(df[columns].sum(axis=1), axis=0).multiply(100).round({'Actual': 2, 'Predicted': 2,'new_salary': 2})
print(df)
"""
   Gender  Actual  Predicted  new_salary
0  Female   33.00      32.97       34.03
1    male   33.32      33.35       33.32
"""
ax=df.plot(kind='bar',figsize=(15,8),
            width = 0.8,
            color = colors_list,
            edgecolor=None)

for p in ax.patches:
    width = p.get_width()
    height = p.get_height()
    x, y = p.get_xy()
    ax.annotate(f'{height}%\n', (x + width/2, y + height*1.02), ha='center',va='center')  
plt.show()

推荐阅读