matplotlib 按定义的限制更改颜色

8oomwypt  于 6个月前  发布在  其他
关注(0)|答案(1)|浏览(53)

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

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

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)
我需要改变我的正方形的颜色与定义限制

nnvyjq4y

nnvyjq4y1#

LinearSegmentedColormap是错误的工具。我建议将ListedColormapBoundaryNorm一起使用:

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()

字符串
输出量:


的数据

相关问题