这是我使用 pandas、numpy 和 seaborn 的解决方案:
import pandas as pd
import numpy as np
import seaborn
import matplotlib.pyplot as plt
# Create summaryTable
ageGroups = np.array(["18-25","26-40"])
categories = np.array(['A','B','C','D','E'])
summaryTable = pd.DataFrame(index=ageGroups, columns=categories)
ageGroupsInts = np.array([18,25,26,40])
counter = 0
for i in range(0, ageGroupsInts.shape[0], 2):
inAgeGroupI = df.loc[df.Age >= ageGroupsInts[i]].loc[df.Age <= ageGroupsInts[i+1]]
numEntries = inAgeGroupI.shape[0]
for j in range(categories.shape[0]):
df_catJ = inAgeGroupI.loc[inAgeGroupI.Category == categories[j]]
summaryTable.at[ageGroups[counter], categories[j]] = df_catJ.shape[0] / numEntries * 100
counter += 1
# Create heatmap
summaryTable_np = summaryTable.to_numpy().astype(float)
xLabels = categories
yLabels = ageGroups
seaborn.heatmap(summaryTable_np, annot=True, linewidths=.5, square=True,
xticklabels=xLabels, yticklabels=yLabels,
vmin=np.amin(summaryTable_np), vmax=np.amax(summaryTable_np), cmap='Reds')
plt.yticks(rotation=0)
其中df 是一个 (nRows,2) 大小的数据框,包含“年龄”和“类别”列,summaryTable 是一个数据框,其中年龄组为行,A-E 类别为列。
这是一个示例输出热图: