Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 None 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

like image 222
leftaroundabout Avatar asked Feb 12 '26 11:02

leftaroundabout


1 Answers

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

like image 88
Tim Fuchs Avatar answered Feb 14 '26 00:02

Tim Fuchs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!