Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overlay pcolormeshes in matplotlib

I want to overlay differently colored regions with pcolormesh. The masked regions do indeed not show up, but they cover other complementary regions. Below is an example where I first plot both regions separately (so the masking works nicely), but then I want to overlay them, however the second one covers the first one. How can I get a plot where the different regions are colored differently?

#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt

xi=np.linspace(0,10,100)
yi=np.linspace(0,10,150)

x=0.5*(xi[1:]+xi[:-1])
y=0.5*(yi[1:]+yi[:-1])

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

Z = np.exp(-(X-5)**2-(Y-5)**2)

Z1 = Z.copy()
Z1[(X+Y)<10]=np.nan

Z2 = Z.copy()
Z2[(X+Y)>=10]=np.nan

plt.figure(figsize=(4,12),tight_layout=True)

plt.subplot(3,1,1)
plt.pcolormesh(x,y,Z1,cmap='Greens',vmin=0,vmax=Z.max())

plt.subplot(3,1,2)
plt.pcolormesh(x,y,Z2,cmap='Blues',vmin=0,vmax=Z.max())

plt.subplot(3,1,3)
plt.pcolormesh(x,y,Z1,cmap='Greens',vmin=0,vmax=Z.max())
plt.pcolormesh(x,y,Z2,cmap='Blues',vmin=0,vmax=Z.max())

Edit:

I should add that the whole thing works nice if I use contourf instead of pcolormesh, but then there is an ugly empty area in between them, as shown below. Alternate question: how do I get rid of that area when using contourf?

like image 577
John Smith Avatar asked Nov 22 '25 02:11

John Smith


1 Answers

You need to make the masked array with the numpy masking module instead of just doing np.nan. Change Z2[(X+Y)>=10]=np.nan to Z2 = np.ma.masked_array(Z, (X+Y)>=10).

like image 174
Amy Teegarden Avatar answered Nov 23 '25 16:11

Amy Teegarden



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!