按定义的限制更改颜色

问题描述 投票:0回答:1

我来这里是因为我不知道如何用seaborn改变我的相关矩阵的颜色。

这是我的情节(故意不显示标签名称):

enter image description here

这是我的代码:

corr = df_corr
corr = corr.fillna(0)

f, ax = plt.subplots(figsize=(15, 9))
f.set_facecolor('#061ab1')

myColors = ((0.0, 0.0, 0.5, 1.0), (0.0, 0.0, 1, 1), (1, 1, 1,1), (1, 0.0, 0.0, 1.0), (0.5, 0.0, 0.0, 1.0))
cmap = LinearSegmentedColormap.from_list('Custom', myColors, len(myColors))

ax = sns.heatmap(corr, cmap=cmap, linewidths=.5, linecolor='lightgray',annot= True, fmt=".2f", color = 'w')
annot_kws={'fontsize': 12, 'fontstyle': 'italic', 'color':'white'}

plt.xticks(rotation=20, color = 'white', size = 10)
plt.yticks(rotation=0, color = 'white',size = 10)

colorbar = ax.collections[0].colorbar
colorbar.set_ticks([-0.667, -0.334,0,0.334, 0.667])
colorbar.set_ticklabels(['Forte corrélation \n négative', 'Correlation négative', 'Corrélation faible','Corrélation positive','Forte corrélation \n positive'], color ='white')
_, labels = plt.yticks()
plt.setp(labels, rotation=0)

plt.show()

我的需求:

我想要这些颜色: 深蓝色,蓝色,白色,红色,深红色 有这些限制: (-1-0.6),(-0.6,-0.2),(-0.2,0.2),(0.2,0.6),(0.6,1)

我需要用定义的限制来改变我的方块的颜色

python matplotlib seaborn heatmap
1个回答
0
投票

LinearSegmentedColormap
是不适合这项工作的工具。我建议将
ListedColormap
BoundaryNorm
:

import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap, BoundaryNorm
import seaborn as sns
import numpy as np

corr = np.random.rand(6, 6)*2 - 1

f, ax = plt.subplots(figsize=(15, 9))
f.set_facecolor('#061ab1')

cmap = ListedColormap([(0, 0, 0.5), (0, 0, 1), (1, 1, 1), (1, 0, 0), (0.5, 0, 0)])
boundaries = [-1, -0.6, -0.2, 0.2, 0.6, 1]
norm = BoundaryNorm(boundaries, 5)

ax = sns.heatmap(corr, cmap=cmap, linewidths=.5, linecolor='lightgray',annot= True, fmt=".2f", color ='w', norm=norm)
annot_kws={'fontsize': 12, 'fontstyle': 'italic', 'color':'white'}

plt.xticks(rotation=20, color = 'white', size = 10)
plt.yticks(rotation=0, color = 'white',size = 10)

colorbar = ax.collections[0].colorbar
colorbar.set_ticks([(boundaries[i]+boundaries[i+1])/2 for i in range(len(boundaries)-1)])
colorbar.set_ticklabels(['Forte corrélation \n négative', 'Correlation négative', 'Corrélation faible','Corrélation positive','Forte corrélation \n positive'], color ='white')

plt.show()

输出:

© www.soinside.com 2019 - 2024. All rights reserved.