简体   繁体   中英

Python heatmap and colorbar colors are different

I'm using matplotlib and seaborn to create a heatmap of my correlation matrix with specific colors representing dataranges. I am facing an issue where my colorbar does not represent the full spectrum of colors in the heatmap. edit: The issue lies with the colorbar in the range -0.5 to -0.3. The color here should be "royal blue." The correct color is represented in the heatmap but not the colorbar.

看图片

Here is my code for the heatmap:

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)

This is applied to my data, 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()

Thanks!

It looks like a seaborn issue. When using pure 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])

the result is as expected.

在此处输入图片说明

To replicate the exact look of the seaborn plot is a bit more work then,

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

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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