taurus
taurus

Reputation: 500

Matplotlib Colormap Set to Black Below Threshold

I am using imshow to plot a sparse matrix and would like for 0 entries to be colored black. I followed the advice given in this answer, but my plot still has white for 0 entries, which is confusing since the highest weighted entries are hot yellow. Any help is much appreciated.

Here is my code:

cmap1 = cm.get_cmap('inferno', 128)
cmap1.set_under(color='black')
im_plot = ax1.imshow(P_im,cmap=cmap1,norm=LogNorm(vmin=1e-30, vmax=np.max(P_im)+1e-15))
ax1.set_title("Title",size=10)

Upvotes: 1

Views: 1354

Answers (1)

Zephyr
Zephyr

Reputation: 12524

Check this code:

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

fig, ax1 = plt.subplots(1, 1, figsize = (4, 4))

x = np.random.binomial(n = 1, p = 0.1, size = (20, 20))

cmap1 = cm.get_cmap('Greys_r', 2)
im_plot = ax1.imshow(x, cmap = cmap1)
ax1.set_title("Title", size = 10)

plt.show()

which gives me this image:

enter image description here

I used x = np.random.binomial(n = 1, p = 0.1, size = (20, 20)) to generate a random sparse matrix, replace it with your data.

Upvotes: 1

Related Questions