热图可视化值的百分比
Heatmap to visualize percentage of values
我正在寻找可视化下面的结果,通过使用热图按列对我的数据进行分组。
数据
Classroom Subject Student
0 A Mathematics A.B.
1 B Computer Science G.M.
2 A Computer Science J.K.
3 B Literature S.R.
4 B Computer Science A.M.
5 A Literature S.R.
6 B Mathematics S.E.
7 C Literature S.T.
8 C Mathematics R.B.
9 A Mathematics B.K.
分组后df.groupby(["Classroom", "Subject"]).size()
,我有
Classroom Subject
A Mathematics 226
Literature 12
Computer Science 122
B Mathematics 1
Literature 14
Computer Science 19
History 22
Geography 238
C Mathematics 5
Literature 15
根据我在网上找到的内容,Seaborn
可能是创建热图并显示值百分比(.sum()/len(df))*100)
,如果我是对的)的最佳解决方案。这个解决方案 对我的问题肯定有帮助,即使它没有使用 seaborn 进行可视化。
这样做
df.groupby(["Classroom", "Subject"]).size()/len(df)*100
我得到值的百分比。我还需要使用热图绘制这些结果。如果您能对此提供一些帮助,我将不胜感激。
Seaborn 的热图使用数据框的列和索引。 Pandas' pivot()
和 pivot_table()
可以创建合适的数据框:
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
df = pd.DataFrame(
{'Classroom': np.random.choice(['A', 'B', 'C'], 1000),
'Subject': np.random.choice(['Mathematics', 'Literature', 'Computer Science', 'History', 'Geography'], 1000),
'Student': [''.join(np.random.choice([*'VWXYZ'], 7)) for _ in range(1000)]})
pivoted = pd.pivot_table(df, values='Student', index='Subject', columns='Classroom', aggfunc='count') / len(df) * 100
ax = sns.heatmap(data=pivoted, annot=True, fmt='.1f')
plt.tight_layout()
plt.show()
我正在寻找可视化下面的结果,通过使用热图按列对我的数据进行分组。
数据
Classroom Subject Student
0 A Mathematics A.B.
1 B Computer Science G.M.
2 A Computer Science J.K.
3 B Literature S.R.
4 B Computer Science A.M.
5 A Literature S.R.
6 B Mathematics S.E.
7 C Literature S.T.
8 C Mathematics R.B.
9 A Mathematics B.K.
分组后df.groupby(["Classroom", "Subject"]).size()
,我有
Classroom Subject
A Mathematics 226
Literature 12
Computer Science 122
B Mathematics 1
Literature 14
Computer Science 19
History 22
Geography 238
C Mathematics 5
Literature 15
根据我在网上找到的内容,Seaborn
可能是创建热图并显示值百分比(.sum()/len(df))*100)
,如果我是对的)的最佳解决方案。这个解决方案
df.groupby(["Classroom", "Subject"]).size()/len(df)*100
我得到值的百分比。我还需要使用热图绘制这些结果。如果您能对此提供一些帮助,我将不胜感激。
Seaborn 的热图使用数据框的列和索引。 Pandas' pivot()
和 pivot_table()
可以创建合适的数据框:
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
df = pd.DataFrame(
{'Classroom': np.random.choice(['A', 'B', 'C'], 1000),
'Subject': np.random.choice(['Mathematics', 'Literature', 'Computer Science', 'History', 'Geography'], 1000),
'Student': [''.join(np.random.choice([*'VWXYZ'], 7)) for _ in range(1000)]})
pivoted = pd.pivot_table(df, values='Student', index='Subject', columns='Classroom', aggfunc='count') / len(df) * 100
ax = sns.heatmap(data=pivoted, annot=True, fmt='.1f')
plt.tight_layout()
plt.show()