leftaroundabout leftaroundabout - 6 months ago 26
Python Question

How do I make a colour plot with undefined regions?

Say I have a function like

def coulomb(x,y):
r = sqrt(x**2 + y**2)
return 1/r if r > 1 else None

How could I best plot this in a colour plot so every
value simply gets rendered as e.g. white, and only the actual number values assigned to the colour scale? Like,

fig = plt.figure()

xs, ys = meshgrid(linspace(-5, 5, n), linspace(-5, 5, n))
vs = 1/sqrt(xs**2 + ys**2)

ax = fig.add_subplot(1, 1, 1, aspect='equal')
fig.colorbar(ax.pcolor(xs,ys,vs, vmin=0, vmax=1))

The function plot without the excluded domain.

but with the center area blank instead of deep-red.

Center erased


Just use masked arrays:

from numpy import ma
vs_ma = ma.masked_where(vs > 1, vs)
plt.colorbar(plt.pcolor(xs, ys, vs_ma, vmin=0, vmax=1))

enter image description here

matplotlib has a more complicated example image_masked.py where you can select the color for masked zones. To convert between an ordinary array and a masked array you can use one of the numpy.ma.masked_* functions