python - Seaborn 热图自定义颜色图

标签 python matplotlib seaborn heatmap

您好,我刚刚为 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)

如您所见,我的输出有两个蓝色列,但我定义了不同的颜色:

As you can see there is two blue column

最佳答案

如果您使用 BoundaryNorm ,您可以为边界之间的范围指定颜色。要获得 4 个范围,您需要 5 个边界。一种方法是在末尾添加一个额外的边界。在这个问题中,不清楚你想用与边界不重合的颜色值做什么。在下面的代码中,颜色用于边界值和直到下一个边界的范围。

import seaborn as sns
import numpy as np
import matplotlib
import matplotlib.pyplot as plt

matrix = np.array([[149030, 34], [7442, 12]])
boundaries = [value for value in matrix.flatten().tolist()]
list.sort(boundaries)
colors = ["#90AFC5", "#336B87", "#2a3132", "#763626"]
norm = matplotlib.colors.BoundaryNorm(boundaries=boundaries + [boundaries[-1]], ncolors=256)

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,
            cmap=cmap,
            norm=norm,
            cbar=True,
            cbar_kws={'format': '%.0f%%', 'ticks': boundaries, 'drawedges': True},
            xticklabels=False,
            yticklabels=False)
plt.show()

resulting plot

关于python - Seaborn 热图自定义颜色图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62678213/

相关文章:

python - matplotlib.pyplot.hist 返回一个直方图,当我有不同的数据时,所有 bin 都具有相同的值

python - 在 Matplotlib 中获取图例作为单独的图片

python - 不规则间隔的热图

python - 设置 Seaborn 热图上颜色条的最大值

python - QAction 可以用于多个任务吗?

Python 3.6 项目结构导致 RuntimeWarning

python - 定义一个函数,为 python 中给出的每个输入重复命令

python - 如何在 matplotlib 中按列而不是行迭代子图

Python - 当行索引和列都是类别时数据帧值的散点图

python - Mayavi:在 triangular_mesh 中插入面部颜色