【问题标题】:How to plot the scatter chart by counting employee numbers using python如何通过使用python计算员工人数来绘制散点图
【发布时间】:2019-12-19 16:41:11
【问题描述】:

我有一个如下数据集:

Employee_No    Hire_Date    Status
000001         01/23/2019    T
000002         01/28/2019    A
000003         02/02/2019    A
000004         02/06/2019    A
000005         02/08/2019    T

我想通过使用 seaborn 来绘制这样的图表:

我希望 X 轴是按月份分组的雇用日期。 Y 轴是员工人数。点应按状态着色(无论它们是活动的还是终止的)。

我试过了:

sns.scatterplot(x = 'Hire_Date', y = 'employee_No', hue = 'target', data = workdata1)

我不知道如何执行计数功能并将x数据分组到月份。

有人可以帮忙吗?

【问题讨论】:

  • 我仍然不确定我是否了解您的数据将如何显示,Y 轴上的员工人数应该是多少?可以根据一些数据手工绘制一些例子来理解你想要的输出吗?

标签: python group-by data-visualization seaborn


【解决方案1】:

您可以使用 pandas 中的分组来实现。导入库。

import pandas as pd
import seaborn as sns

然后将您的数据导入数据框。

df = pd.read_csv("data.csv")

    Employee_No     Hire_Date   Status
0   1   1/23/2019   T
1   2   1/28/2019   A
2   3   2/2/2019    A
3   4   2/6/2019    A
4   5   2/8/2019    T
5   6   3/1/2019    A
6   7   3/7/2019    A
7   8   3/15/2019   T
8   9   4/18/2019   A
9   10  4/29/2019   T

确保将日期列类型更改为日期时间

df['Hire_Date'] = pd.to_datetime(df['Hire_Date'])

拥有一个整洁的数据框才能使用 seaborn 散点图很重要,所以让我们添加年份和月份列。

df['year']= df['Hire_Date'].map(lambda x: x.year)
df['month'] = df['Hire_Date'].map(lambda x: x.month)

现在,如果您按月和状态分组,您会得到每个月的已终止和在职员工

df.groupby(["month","Status"]).count().Employee_No

month  Status  Employee_No Count
1      A         1
       T         1
2      A         2
       T         1
3      A         2
       T         1
4      A         1
       T         1

为了能够在sns中使用散点图重置分组操作的索引

df_tidy = df.groupby(["month","Status"]).count().reset_index()

现在使用散点图:

sns.scatterplot(x = 'month', y = 'Employee_No', hue='Status', data = df.tidy)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-14
    • 2018-06-23
    • 2022-01-27
    • 1970-01-01
    • 2013-05-12
    • 1970-01-01
    • 2019-11-24
    • 2017-07-21
    相关资源
    最近更新 更多