matplotlib 按定义的限制更改颜色

8oomwypt  于 2023-11-22  发布在  其他
关注(0)|答案(1)|浏览(217)

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

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

enter image description here

这里是我的代码:

  1. corr = df_corr
  2. corr = corr.fillna(0)
  3. f, ax = plt.subplots(figsize=(15, 9))
  4. f.set_facecolor('#061ab1')
  5. 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))
  6. cmap = LinearSegmentedColormap.from_list('Custom', myColors, len(myColors))
  7. ax = sns.heatmap(corr, cmap=cmap, linewidths=.5, linecolor='lightgray',annot= True, fmt=".2f", color = 'w')
  8. annot_kws={'fontsize': 12, 'fontstyle': 'italic', 'color':'white'}
  9. plt.xticks(rotation=20, color = 'white', size = 10)
  10. plt.yticks(rotation=0, color = 'white',size = 10)
  11. colorbar = ax.collections[0].colorbar
  12. colorbar.set_ticks([-0.667, -0.334,0,0.334, 0.667])
  13. 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')
  14. _, labels = plt.yticks()
  15. plt.setp(labels, rotation=0)
  16. plt.show()

字符串

我的需求:

我想有这些颜色:深蓝色,蓝色,白色,红色,暗红色与这些限制:(-1-0.6),(-0.6,-0.2),(-0.2,0.2),(0.2,0.6),(0.6,1)
我需要改变我的正方形的颜色与定义限制

nnvyjq4y

nnvyjq4y1#

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

  1. import matplotlib.pyplot as plt
  2. from matplotlib.colors import ListedColormap, BoundaryNorm
  3. import seaborn as sns
  4. import numpy as np
  5. corr = np.random.rand(6, 6)*2 - 1
  6. f, ax = plt.subplots(figsize=(15, 9))
  7. f.set_facecolor('#061ab1')
  8. cmap = ListedColormap([(0, 0, 0.5), (0, 0, 1), (1, 1, 1), (1, 0, 0), (0.5, 0, 0)])
  9. boundaries = [-1, -0.6, -0.2, 0.2, 0.6, 1]
  10. norm = BoundaryNorm(boundaries, 5)
  11. ax = sns.heatmap(corr, cmap=cmap, linewidths=.5, linecolor='lightgray',annot= True, fmt=".2f", color ='w', norm=norm)
  12. annot_kws={'fontsize': 12, 'fontstyle': 'italic', 'color':'white'}
  13. plt.xticks(rotation=20, color = 'white', size = 10)
  14. plt.yticks(rotation=0, color = 'white',size = 10)
  15. colorbar = ax.collections[0].colorbar
  16. colorbar.set_ticks([(boundaries[i]+boundaries[i+1])/2 for i in range(len(boundaries)-1)])
  17. 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')
  18. plt.show()

字符串
输出量:


的数据

展开查看全部

相关问题