python - Seaborn 热图中的自定义调色板

标签 python matplotlib seaborn

我使用以下命令绘制了以下相关矩阵“corr”:

import seaborn as sns; 
sns.set()
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(6,6))
ax = sns.heatmap(corr, annot=True, fmt="0.2f", linewidths=.5)

enter image description here

有没有办法创建一个围绕 0 对称的调色板。如果可能的话,在 0 附近呈现绿色色调,在接近 +1 或 -1 时呈现红色色调。这样,绿色(或冷色)表示“无相关性”,红色(暖色)表示“高相关性”(正相关或负相关)。

谢谢。

最佳答案

一个LinearSegmentedColormap.from_list可以使用。为了让绿色正好位于中心,vminvmax 需要对称设置为零。

import seaborn as sns; sns.set()
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
import numpy as np

corr = np.corrcoef(np.random.random(((5, 5))))

fig, ax = plt.subplots(figsize=(6,6))

cmap = LinearSegmentedColormap.from_list('RedGreenRed', ['crimson', 'lime', 'crimson'])
ax = sns.heatmap(corr, cmap=cmap, vmin=-1, vmax=1, annot=True, fmt="0.2f", linewidths=.5)
plt.show()

example plot

PS:在红色和绿色之间添加黄色可能看起来更好:LinearSegmentedColormap.from_list('', ['crimson', 'gold', 'lime', 'gold', 'crimson'])

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

相关文章:

Python用完整列表填充列表中缺失的条目

Python Colormap 用于显示高值范围内的差异

python - 使用 matplotlib savefig 保存文件对象,从多个 svg 图形创建 tar 文件

python - 如何在 Seaborn/Matplotlib 中将所有边缘颜色设置为无?

python - ValueError : Classification metrics can't handle a mix of multilabel-indicator on pretrained CNN

python - Jenkins 构建的 Django 应用程序的 Docker 容器中的错误时间

python - Seaborn:标注线性回归方程

python - Python中Pandas/Matplotlib中直方图和密度的叠加

python - 使用for循环在python中分配数组值

python - matplotlib 中的日期刻度和旋转