Mitchell van Zuylen
Mitchell van Zuylen

Reputation: 4125

Remove masked items from the figure in seaborn.heatmap

If one masks certain elements in a seaborn heatmap using the mask option, the mask plots white space on top of the figure, as can be seen here in this quick example.

# generate some random data
x = [np.random.rand() for x in range(0,20)]
y = [np.random.rand() for y in x]
data = pd.DataFrame([x,y]) # cast it into a dataframe
corr = data.corr() # get the correlation values


# generate a mask
mask = []
l = [True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, False, False]
for i in range(0,10):
    mask.append([True for x in range(0,20)])
for i in range(0,10):
    mask.append(l)
mask = np.array(mask)

sb.heatmap(corr,mask=mask)

enter image description here

Is there a way to plot the image, so that the masked area is removed from the plot, so that it appears more like the following:

enter image description here

Upvotes: 1

Views: 2030

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339340

You can remove all the columns and rows from the dataframe for which the mask is True throughout.

masked_corr = corr.loc[~np.all(mask, axis=1), ~np.all(mask, axis=0)]
sns.heatmap(masked_corr)

will produce

enter image description here

Upvotes: 2

Related Questions