基于 Python 中的多个特征生成热图

Generating heatmaps based on multiple features in Python

我有一个如下所示的数据框:

student    Time                              presence
  A      04/03/2022 21:52:55.446                 1
  A      04/03/2022 21:55:55.446                 0
  A      04/03/2022 21:56:55.446                 0
  B      04/03/2022 21:52:55.446                 1
  B      04/03/2022 21:55:55.446                 1
  B      04/03/2022 21:56:55.446                 0

我正在尝试创建一个按学生分组的热图,其中 X 轴是时间,Y 轴是学生。颜色基于存在特征。我对 seaborn 和 calplot 感到困惑,不知道如何处理它。

sns.heatmap's documentation 提到了一个示例,其中 pandas' pivot 用于创建航班数据的热图。以下是如何将其应用于给定数据的示例:

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
from io import StringIO

df_str = '''student    Time                              presence
A      "04/03/2022 21:52:55.446"                 1
A      "04/03/2022 21:55:55.446"                 0
A      "04/03/2022 21:56:55.446"                 0
B      "04/03/2022 21:52:55.446"                 1
B      "04/03/2022 21:55:55.446"                 1
B      "04/03/2022 21:56:55.446"                 0'''
df = pd.read_csv(StringIO(df_str), delim_whitespace=True)
df['HourMin'] = df['Time'].apply(lambda t: t[11:16])
df_pivoted = df.pivot('student', 'HourMin', 'presence')
sns.heatmap(data=df_pivoted, cmap=['lightcoral', 'lime'], cbar=False, lw=2)
plt.tight_layout()
plt.show()