努力在 Python 中插入饼图

Struggling to insert a pie chart in Python

我使用 excel sheet 制作了饼图,但结果不完整。我不确定原因。这是代码:

import matlotplib.pyplot as plt
import pandas as pd
import numpy as np
Employee=pd.read_excel("C:\Users\Jon\Desktop\data science\Employee.xlsx")
Employee

colors = ["#1f77b4", "#ff7f0e"]
group_by_departments=Employee.groupby("Department").count().reset_index()
sizes = group_by_departments['Gender']
labels = group_by_departments['Department']
plt.pie(sizes, labels=labels, colors = colors,autopct='%.2f %%')
plt.show()

您可以使用 .size() 来获取每个组的计数。您需要同时按部门和性别分组以获得所有子组的个体计数。

这是一些示例代码:

from matplotlib import pyplot as plt
import pandas as pd
import numpy as np

N = 100
Employee = pd.DataFrame({'Gender': np.random.choice(['Male', 'Female'], N),
                         'Department': np.random.choice(['IT', 'Sales', 'HR', 'Finance'], N),
                         'Age': np.random.randint(20, 65, N),
                         'Salary': np.random.randint(20, 100, N) * 1000})
colors = ["turquoise", "tomato"]
group_by_departments_and_gender = Employee.groupby(["Department", "Gender"]).size().reset_index(name='Counts')
sizes = group_by_departments_and_gender['Counts']
labels = [f'{dept}\n {gender}' for dept, gender in group_by_departments_and_gender[['Department', 'Gender']].values]
plt.pie(sizes, labels=labels, colors=colors, autopct='%.2f %%')
plt.tight_layout()
plt.show()

PS:您可以通过以下方式为每个性别分配颜色:

colors = ["magenta" if gender=="Male" else "deepskyblue" for gender in group_by_departments_and_gender["Gender"]]

如果其中一个部门不存在其中一种性别,这尤其有用。