如何在 python 上绘制图表,其中有两个 x 变量,其中一个需要根据给定数据计算?

How to draw a graph on python where there are two x-variables, one of which needs to be calculated from given data?

我有一个 CSV 文件,其中包含一项调查的结果,其中要求用户回答他们的年龄(0 到 100)和他们的情绪(0=快乐 1=中期 2=悲伤)。我打算使用 matplotlib 或任何其他图形库在 python 上制作一个条形图,在 y 轴上显示每个年龄段的人数,然后在 x 轴上显示一个三重条形图来显示有多少人悲伤,快乐每个年龄段都有中等人。问题是在CSV文件中没有直接包含每个年龄段的总人数,每个年龄段的快乐人数和每个年龄段的悲伤人数等数据的列。有关如何解决的任何提示解决这个问题会很有帮助。下面的 table 显示了 CSV 文件的几行。谢谢

Age Mood level
12 0
83 1
55 ​ 2

假设我们有以下数据框:

import pandas as pd
from matplotlib import pyplot as plt

df = pd.DataFrame(
    {
        "Age": [20, 16, 16, 20, 20, 16, 18, 18, 18, 20, 16, 16, 18, 18, 18, 20, 20],
        "Mood Level": [0, 2, 1, 2, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 2, 2, 1],
    }
)

然后我们需要根据情绪水平创建一些编码,这意味着我们需要创建值为 0(假)或 1(真的)。这可以通过以下方式完成:

df = pd.concat([df, pd.get_dummies(df["Mood Level"], prefix="Mood_Level")], axis=1)

并会导致:

    Age  Mood level  Mood_Level_0  Mood_Level_1  Mood_Level_2
0    20           0             1             0             0
1    16           2             0             0             1
2    16           1             0             1             0
3    20           2             0             0             1
4    20           0             1             0             0
5    16           1             0             1             0
6    18           0             1             0             0
7    18           1             0             1             0
8    18           1             0             1             0
9    20           0             1             0             0
10   16           0             1             0             0
11   16           1             0             1             0
12   18           0             1             0             0
13   18           1             0             1             0
14   18           2             0             0             1
15   20           2             0             0             1
16   20           1             0             1             0

最后,我们需要按年龄分组并对上面创建的每个列的 1 求和:

grouped_per_age = df.groupby(["Age"], as_index=True,).agg(
    mood_level_0=("Mood_Level_0", "sum"),
    mood_level_1=("Mood_Level_1", "sum"),
    mood_level_2=("Mood_Level_2", "sum"),
)

这将导致:

     mood_level_0  mood_level_1  mood_level_2
Age
16              1             3             1
18              2             3             1
20              3             1             2

绘制上面的数据框:

ax = grouped_per_age.plot.bar(rot=0)
plt.xlabel("Age")
plt.ylabel("Count")
plt.legend()
plt.show()

结果: