Question

Let's assume I have two numpy arrays (The ones I present are just examples):

import numpy as np
A = np.arange(144).reshape((12, 12))
np.random.shuffle(A)

B = np.ones((12,12))
B[0:10:4,:] = None

I want to plot A using imshow:

import matplotlib.pyplot as mplt
mplt.imshow(A, cmap = mplt.gray())

and overlay B so that the None areas are fully transparent and the one areas have an alpha of (e.g. alpha = 0.3.).

I already tried using something along the lines of:

mplt.imshow(B, cmap = mplt.get_cmap('Reds), alpha = 0.3)

but that does not work. Also tried to use masked arrays to create B, but cannot get my head around it. Any suggestions?

Thanks

EDIT:

I ended up using

my_red_cmap = mplt.cm.Reds
my_red_cmap.set_under(color="white", alpha="0")

which works like a charm (I tested Bill's solution as well, which also works perfectly).

Était-ce utile?

La solution

If instead of None you use 0's for the transparent colors, you can take your favorite matplotlib colormap and add a transparent color at the beginning of it:

my_red_cmap = mplt.cm.Reds
my_red_cmap.set_under(color="white", alpha="0")

then you can just plot the array B with a global alpha of 0.3 whatever you want, using your custom color map, which will use a transparent white as its first value.

Autres conseils

You can do the following:

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

x = np.arange(100).reshape(10, 10)
y = np.arange(-50, 150, 2).reshape(10, 10)
y[y<x] = -100 # Set bad values

cmap1 = cm.gray
cmap2 = cm.Reds
cmap2.set_under((1, 1, 1, 0))

params = {'interpolation': 'nearest'}
plt.imshow(x, cmap=cmap1, **params)
plt.show()

enter image description here

plt.imshow(y, cmap=cmap2, **params)
plt.show()

enter image description here

plt.imshow(x, cmap=cmap1, **params)
plt.imshow(y, cmap=cmap2, vmin=0, **params) # vmin > -100
plt.show()

enter image description here

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top