Variable alpha blending in pylab

How to control transparency over a 2D image in pylab? I would like to give two sets of values (X,Y,Z,T) , where X,Y are arrays of positions, Z is the color value, and T is transparency for a function like imshow , but it seems that the function only accepts an alpha scalar . As a specific example, consider the code below that tries to display two Gaussians. The closer the value is to zero, the more transparent I would like the chart to be.

 from pylab import * side = linspace(-1,1,100) X,Y = meshgrid(side,side) extent = (-1,1,-1,1) Z1 = exp(-((X+.5)**2+Y**2)) Z2 = exp(-((X-.5)**2+(Y+.2)**2)) imshow(Z1, cmap=cm.hsv, alpha=.6, extent=extent) imshow(Z2, cmap=cm.hsv, alpha=.6, extent=extent) show() 

Note. I'm not looking for a Z1 + Z2 plot (that would be trivial), but for a general way, specify alpha blending in the image.

+7
python matplotlib alphablending
source share
1 answer

One thing you can do is change what you put in imshow. The first variable can be the grayscale values ​​you used, or it can be RGB or RGBA values. If you use RGB / RGBA values, CMAP is ignored. For example,

 imshow(Z1, cmap=cm.hsv, alpha=.6, extent=extent) 

will generate the same image as

 imshow(cm.hsv(Z1), alpha=.6, extent=extent) 

because cm.hsv() just returns RGBA values. If you look at the values ​​it returns, they all have 1.0 as the value of A (transparency). Thus, one way to make the variables transparent is something like this:

 def mycmap(x): tmp = cm.hsv(x) for i in xrange(tmp.shape[0]): for j in xrange(tmp.shape[0]): tmp[i,j][3] = somefunction of x[i,j] that generates the transparency return tmp imshow(mycmap(Z1), extent=extent) imshow(mycmap(Z2), extent=extent) 

You may find a slightly more elegant way to do this, but hopefully you get this idea.

+7
source share

All Articles