可能存在较少涉及的方式。以下方法循环遍历类别;对于每个类别,热图都用相应的颜色填充。
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import seaborn as sns
import pandas as pd
import numpy as np
from io import StringIO
data_str = '''ID Cat V1 V2 V3
1 A 1 1 1
2 B 1 1 1
3 A 1 1 0
4 C 0 0 0'''
df = pd.read_csv(StringIO(data_str), delim_whitespace=True)
df = df.set_index('ID')
fig, ax = plt.subplots(figsize=(6, 6))
categories = ['A', 'B', 'C']
colors = ['crimson', 'lime', 'dodgerblue']
for cat, color in zip(categories, colors):
df_cat = df[['V1', 'V2', 'V3']][df['Cat'] == cat].reindex(df.index, fill_value=0)
df_cat[['V1', 'V2', 'V3']] = df_cat[['V1', 'V2', 'V3']].replace({0: np.nan})
if not np.all(df_cat.isna()):
sns.heatmap(data=df_cat, cmap=ListedColormap([color]), cbar=False, lw=1, alpha=1, ax=ax)
plt.show()