嗨,我需要从只有两列的数据框中绘制热图。这些列由大约300行组成。每一行都有一个用户分配的类别(A-E)和1-5之间的分数。
我想将每个类别的用户得分百分比显示为热图。
例如:
1 2 3 4 5
A 70% 10% 10% 5% 5%
B 50% 20% 10% 8% 2%
C 30% 40% 10% 10% 10%
D 10% 30% 20% 30% 10%
E 20% 20% 40% 15% 5%
提前感谢!
发布于 2020-08-28 00:16:14
以下是我使用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
是用户得分百分表。
下面是一个热图示例:
https://stackoverflow.com/questions/63264054
复制相似问题