5

I try to plot a layer on an imshow. This layer is based on a matrix where every values are equals to 0 but some specific pixels are equals to 1.

If I use the alpha parameter, I'm loosing mycolor as well... How can I have 0% transparency where I have a "1" value in my layer and 100% transparency where it is equals to 0 ?

Here is an example:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0,5,6)
y = x

X, Y = np.meshgrid(x,y)

Z = (X**2+Y-11)**2

plt.imshow(Z,cmap='jet')

layer = np.zeros((6,6))
layer[3,3] = 1
layer[2,4] = 1
plt.imshow(layer,alpha=0.1,cmap = 'Purples')

thx for your help!

Edit: How I tried to give an alpha matrix

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0,5,6)
y = x

X, Y = np.meshgrid(x,y)

Z = (X**2+Y-11)**2

plt.subplot(1,3,1)
plt.imshow(Z,cmap='jet')

layer = np.zeros((6,6))
layer[3,3] = 1
layer[2,4] = 1

alphas = layer.copy()

alphas[alphas==0]=0.1
alphas[alphas==1]=0.9


plt.subplot(1,3,2)
plt.imshow(layer,alpha=0.9,cmap = 'Reds')

plt.subplot(1,3,3)
plt.imshow(Z,cmap='jet')
plt.imshow(layer,alpha=alphas,cmap = 'Reds')
lelorrain7
  • 315
  • 5
  • 13
  • I'm not familiar with masks. If I understand well, the "mask" is applied on the data, not on the picture. right ? If yes, prefer not to modify my initial picture and continue to use my "layer". I was thinking to use for example a matrix of alphas to define the transparency square by square. But it seems it is not working (or I'm doing it wrong) – lelorrain7 Jul 22 '19 at 12:49

1 Answers1

5

You can use the idea of masking as given here. Here, masked_where will return a MaskedArray which will be masked if layer=0 and 1 if layer=1. This way, you will get a 100% transparency where layer is equals to 0 and 0% transparency where layer is "1"

ax = plt.subplot(1,3,1)
plt.imshow(Z,cmap='jet')

layer = np.zeros((6,6))
layer[3,3] = 1
layer[2,4] = 1

masked = np.ma.masked_where(layer == 0, layer)
ax.imshow(masked,alpha=1,cmap = 'Reds')
plt.show()

enter image description here

Sheldore
  • 37,862
  • 7
  • 57
  • 71
  • Okkk, I was ignoring this function. I manually tried with a NaN, but is was not working. Thant you, great help! – lelorrain7 Jul 22 '19 at 14:40