【问题标题】:Struggling to insert a pie chart in Python努力在Python中插入饼图
【发布时间】:2021-12-19 23:50:33
【问题描述】:

我使用 Excel 表格制作了一个饼图,但结果不完整。我不确定原因。代码如下:

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

【问题讨论】:

  • Employee 的样本会有所帮助。你是什​​么意思“它出来不完整”?
  • 缺少应该显示“性别”的图例。我不知道它是显示每个部门的员工人数还是只显示一种性别。

标签: python pandas matplotlib pie-chart


【解决方案1】:

您可以使用.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"]]

这在其中一个部门中不存在其中一种性别的情况下特别有用。

【讨论】:

  • 完成。我接受了你的回答
猜你喜欢
  • 2021-08-11
  • 2021-12-15
  • 1970-01-01
  • 2021-02-19
  • 2022-07-08
  • 1970-01-01
  • 2021-03-03
  • 2022-10-30
  • 1970-01-01
相关资源
最近更新 更多