简体   繁体   English

seaborn 热图中的自定义调色板

[英]Customized color palette in seaborn heatmap

I have the following correlation matrix 'corr' drawn using the following commands:我使用以下命令绘制了以下相关矩阵“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)

在此处输入图像描述

Is there a way to create a color palette which is symmetric around 0. With greenish tones around 0, and reddish tones when approaching +1 or -1, if this is possible.有没有办法创建一个围绕 0 对称的调色板。如果可能的话,在 0 附近使用绿色调,在接近 +1 或 -1 时使用红色调。 In this way, green (or cold colors) means 'no correlation', and red (warm colors) means 'high correlation' (either positive or negative).这样,绿色(或冷色)表示“无相关性”,红色(暖色)表示“高相关性”(正或负)。

Thank you.谢谢你。

A LinearSegmentedColormap.from_list can be used.可以使用LinearSegmentedColormap.from_list To have the green exactly in the center, vmin and vmax need to be set symmetric to zero.为了使绿色恰好位于中心,需要将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()

示例图

PS: Adding a yellowish color halfway between red and green could look nicer: LinearSegmentedColormap.from_list('', ['crimson', 'gold', 'lime', 'gold', 'crimson']) PS:在红色和绿色之间添加黄色会更好看: LinearSegmentedColormap.from_list('', ['crimson', 'gold', 'lime', 'gold', 'crimson'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM