kuzand
kuzand

Reputation: 9806

Overlaying two plots using pcolor

I want to plot two numpy arrays Z1 and Z2 in the same figure, Z2 on top of Z1. The array Z2 contains only 0's and 1's, and I want 0's to be fully transparent (alpha = 0) and 1's transparent with some alpha > 0.

Here's the code and the resulting image:

import numpy as np
import matplotlib.pyplot as plt

N = 10
x = np.arange(0, N)
y = np.arange(0, N)
Z1 = np.random.rand(N,N)
Z2 = np.ones((N, N))
Z2[0:N//2, 0:N] = 0

X, Y = np.meshgrid(x, y)
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(8, 6))
plt.pcolormesh(X, Y, Z1, cmap=plt.cm.Blues)
plt.colorbar()
plt.pcolormesh(X, Y, Z2, cmap=plt.cm.Reds_r, alpha=0.3)
ax.set_xlabel(r'$x$', fontsize=22)
ax.set_ylabel(r'$y$', fontsize=22)
plt.show()

enter image description here

There are two problems:

  1. Appearance of the unwanted grid lines

  2. The 0's of Z2 are not fully transparent as needed

To get rid of the grid lines we can use imshow instead of pcolor, but I really want to use the values of x and y.

Upvotes: 3

Views: 4942

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339250

The easiest option to get some of the pixels transparent is to not draw them at all. This would be done by setting them to NaN (not a number).

import numpy as np
import matplotlib.pyplot as plt

N = 10
x = np.arange(0, N)
y = np.arange(0, N)
Z1 = np.random.rand(N,N)
Z2 = np.ones((N, N))
Z2[0:N//2, 0:N] = np.nan

X, Y = np.meshgrid(x, y)
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(8, 6))
plt.pcolormesh(X, Y, Z1, cmap=plt.cm.Blues)
plt.colorbar()
plt.pcolormesh(X, Y, Z2, cmap=plt.cm.Reds, vmin=0,vmax=1,alpha=0.3)
ax.set_xlabel(r'$x$', fontsize=22)
ax.set_ylabel(r'$y$', fontsize=22)
plt.show()

enter image description here

Upvotes: 5

Related Questions