Python热图和颜色栏颜色不同

时间:2018-10-03 12:07:06

标签: python pandas numpy matplotlib seaborn

我正在使用matplotlib和seaborn来创建具有特定颜色代表数据范围的相关矩阵的热图。我遇到一个问题,即我的色条不能代表热图中的所有颜色。 编辑:问题在于颜色栏在-0.5到-0.3范围内。这里的颜色应该是“宝蓝色”。正确的颜色在热图中显示,但在颜色栏中不显示。

see image

这是我的热图代码:

from matplotlib import colors
cmap = colors.ListedColormap(["navy", "royalblue", "lightsteelblue", "beige", "peachpuff", "salmon", "darkred"])
bounds = [-1, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 1]
norm = colors.BoundaryNorm(bounds, cmap.N)

这将应用于我的数据corr_matrix。

#Generate mask for correlation matrix
mask = np.zeros_like(corr_matrix, dtype=np.bool)
mask[np.triu_indices_from(mask)] = True

#print the correlation matrix
fig, ax = plt.subplots()
sns.heatmap(corr_matrix, annot=True, fmt='.4f', cmap=cmap, norm=norm, mask=mask, cbar=True, ax=ax, cbar_kws=dict(ticks=[-1, -0.5, -0.3, -0.1, +0.1, +0.3, +0.5, +1]))
ax.set_title('Correllation Matrix')
ax.set_yticklabels(ax.get_yticklabels(), rotation="horizontal")
plt.show()

谢谢!

1 个答案:

答案 0 :(得分:1)

这看起来像是一个重大问题。使用纯matplotlib时,

im = ax.imshow(np.ma.masked_array(corr_matrix, mask), cmap=cmap, norm=norm)
fig.colorbar(im, ticks=[-1, -0.5, -0.3, -0.1, +0.1, +0.3, +0.5, +1])

结果符合预期。

enter image description here

要复制海洋情节的确切外观,还需要做更多的工作,

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colors

corr_matrix = np.array([[0,0,0,0,0],
                        [-.11,0,0,0,0],
                        [-.1,.34,0,0,0],
                        [-0.06,-.1,-.06,0,0],
                        [-0.32,-.08,-.01,.16,0]])

cmap = colors.ListedColormap(["navy", "royalblue", "lightsteelblue", 
                              "beige", "peachpuff", "salmon", "darkred"])
bounds = [-1, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 1]
norm = colors.BoundaryNorm(bounds, cmap.N)

mask = np.zeros_like(corr_matrix, dtype=np.bool)
mask[np.triu_indices_from(mask)] = True
corr_matrix_masked = np.ma.masked_array(corr_matrix, mask)

fig, ax = plt.subplots()

im = ax.imshow(corr_matrix_masked, cmap=cmap, norm=norm)
fig.colorbar(im, ticks=[-1, -0.5, -0.3, -0.1, +0.1, +0.3, +0.5, +1])

for i in range(corr_matrix_masked.shape[0]):
    for j in range(corr_matrix_masked.shape[1]):
        if not corr_matrix_masked.mask[i,j]:
            val = corr_matrix_masked[i,j]
            color = {True:"w", False:"k"}[np.abs(val) > 0.3]
            ax.text(j,i,"{:.4f}".format(corr_matrix_masked[i,j]), 
                    ha="center", va="center", color=color)

ax.set_title('Correllation Matrix')
for k,v in ax.spines.items():
    v.set_visible(False)
plt.show()

enter image description here