这是我使用 numpy、pandas 和 seaborn 的解决方案:
import numpy as np
import pandas as pd
import seaborn
import matplotlib.pyplot as plt
# Create summaryTable
categories = np.array(['A','B','C','D','E'])
summaryTable = pd.DataFrame(index=categories, columns=np.arange(1,6))
for i in range(summaryTable.shape[0]):
for j in range(summaryTable.shape[1]):
df_ij = df.loc[df.Category == summaryTable.index[i]].loc[df.Score == summaryTable.columns[j]]
numOccurances = df_ij.shape[0]
numOccurancesCat = df.loc[df.Category == summaryTable.index[i]].shape[0]
summaryTable.at[categories[i], j+1] = numOccurances / numOccurancesCat * 100
# Create heatmap
summaryTable_np = summaryTable.to_numpy().astype(float)
xLabels = np.arange(1,6)
yLabels = categories
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 是您的数据框,大约有 300 行和 2 列,summaryTable 是用户得分百分比表。
这是一个示例热图: