python - 如何在条形图中显示百分比而不是值?
问题描述
有我下面的数据框和代码。
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
:有没有办法显示与实际值和预测值相比增加了多少百分比?而不是值,我需要百分比变化。
解决方案
请检查代码段以显示百分比而不是值。刚刚将您的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()
推荐阅读
- python - 如何将线程中的值存储到数据框中,同时从所述数据框中提取值?
- swift - ARSCNView 缩放相机源
- c++ - 使用用户输入乘以变量
- gitlab-ci - 设置适用于 CI 配置中所有作业的变量/配置
- scala - 为什么 Spark DataSet 会丢失其所有架构并仅返回 byte[]?
- javascript - 如何在函数本身的 JS replace() 函数中重用正则表达式的匹配值?
- typescript - 尝试实现一个函数,该函数采用三种可能的参数类型中的两种
- html - 当另一个 div 类在另一个属性中具有特定值时,如何更改 CSS 类属性?
- c# - 在 .NET 中的 Winforms 项目上从 API 打开 Pdf
- google-sheets - 查询引用动态数组