Home > Enterprise >  Overlay of two layers of different shapes with Matplotlib
Overlay of two layers of different shapes with Matplotlib

Time:10-06

I'd like to overlay:

  • x: 1 image (for example here it's a scipy built-in racoon face) of size 1024x768, numpy shape (768, 1024, 3)
  • y: 1 numpy array, with the same aspect ratio, but a different shape (100, 133).

How to imshow them on top of each other? They should both take the full plot width, i.e.:

  • the image should use 1024x768 pixels
  • the array should be interpolated (or not, pixelated), to take the same pixel width 1024.

This doesn't work:

import numpy as np, matplotlib.pyplot as plt, scipy.misc
x = scipy.misc.face(gray=False)     # shape (768, 1024, 3)
y = np.random.random((100, 133))    # shape (100, 133)
fig, (ax0, ax1) = plt.subplots(2, 1, gridspec_kw={'height_ratios': [5, 1]})
img0 = ax0.imshow(x)  
img1 = ax0.imshow(y, cmap="jet", alpha=0.3)
plt.show()

because a small part of the racoon face is displayed.

For reference, here is the full image:

CodePudding user response:

You have to match their extent:

enter image description here

import numpy as np
import matplotlib.pyplot as plt

from scipy.misc import face

x = face(gray=False) # shape (768, 1024, 3)
y = np.random.random((100, 133)) # shape (100, 133)
fig, ax = plt.subplots()
img0 = ax.imshow(x)
img1 = ax.imshow(y, cmap="jet", alpha=0.3, extent=img0.get_extent())
plt.show()
  • Related