您好,我刚刚为seaborn 热图创建了自定义cmap,但是当我想使用它时,它没有显示正确的颜色。我已经一步一步完成了:
import seaborn as sns
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
matrix = np.array([[149030, 34],[7442, 12]])
norm = matplotlib.colors.Normalize(matrix.min(), matrix.max())
boundaries = [value for value in matrix.flatten().tolist()]
list.sort(boundaries)
colors = [[norm(boundaries[0]), "#90AFC5"],
[norm(boundaries[1]), "#336B87"],
[norm(boundaries[2]), "#2a3132"],
[norm(boundaries[3]), "#763626"]]
cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", colors)
fig = plt.figure(figsize=(6, 6))
ax = plt.subplot()
annot = np.array([[f"{matrix[0,0]}", f"{matrix[0,1]}"],
[f"{matrix[1,0]}", f"{matrix[1,1]}"]], dtype=object)
sns.heatmap(matrix,
annot=annot,
annot_kws={"size": 11},
fmt="",
ax=ax,
vmin=matrix.min(),
vmax=matrix.max(),
cmap=cmap,
cbar=True,
cbar_kws={'format': '%.0f%%', 'ticks': boundaries, 'drawedges': True},
xticklabels=False,
yticklabels=False)
Run Code Online (Sandbox Code Playgroud)
如您所见,我的输出有两个蓝色列,但我定义了不同的颜色:
