views:

194

answers:

1

How does one control the transparency over a 2D image in pylab? I'd 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 the transparency to a function like imshow but it seems that the function only takes alpha as a scalar. As a concrete example, consider the code below that attempts to display two Gaussians. The closer the value is to zero, the more transparent I'd like the plot 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 am not looking for a plot of Z1+Z2 (that would be trivial) but for a general way to specify the alpha blending across an image.

+3  A: 

One thing that you can do is modify what you put into imshow. The first variable can be grayscale values as you have used or it can be RGB or RGBA values. If you RGB/RGBA values then the cmap is ignored. So for instance,

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 take a look at the values it returns, they all have 1.0 as the A value (the transparency). So one way to make variable transparency would be 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 might find a little more elegant way of doing this, but hopefully you get the idea.

Justin Peel
This is great and exactly what I was looking for! Looking more into it I see that `imshow` can take a `MxNx4` ie. a Z-array with the colormap predefined by the user. Thanks!
Hooked