I am trying to align multiple subplots with a zoomed inset plot. Something like this:
|‾ ‾ ‾ ‾| |‾ ‾| |‾ ‾| |‾ ‾|
| | |_ _| |_ _| |_ _|
| |
|_ _ _ _|
I want ax2
to be aligned with axins
- i.e. it should be the same size as the zoomed inset plot and placed side-by-side. How do I achieve this with matplotlib?
CodePudding user response:
I've been able to achieve that, but I fear that it only works as long as you use an equal aspect ratio on the second axis (maybe you are plotting another image with height=width):
from matplotlib import cbook
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
import numpy as np
def get_demo_image():
z = cbook.get_sample_data("axes_grid/bivariate_normal.npy", np_load=True)
# z is a numpy array of 15x15
return z, (-3, 4, -4, 3)
gs = GridSpec(1, 2)
fig = plt.figure()
ax1 = fig.add_subplot(gs[0, 0])
ax2 = fig.add_subplot(gs[0, 1])
# make data
Z, extent = get_demo_image()
Z2 = np.zeros((150, 150))
ny, nx = Z.shape
Z2[30:30 ny, 30:30 nx] = Z
ax1.imshow(Z2, extent=extent, origin="lower")
# inset axes....
axins = ax1.inset_axes([1.1, 0.5, 0.5, 0.5])
axins.imshow(Z2, extent=extent, origin="lower")
# sub region of the original image
x1, x2, y1, y2 = -1.5, -0.9, -2.5, -1.9
axins.set_xlim(x1, x2)
axins.set_ylim(y1, y2)
axins.set_axis_off()
ax1.indicate_inset_zoom(axins, edgecolor="black")
ax2.set_aspect("equal")
plt.tight_layout()
plt.show()
CodePudding user response:
Inspired by Davide_sd's answer it is possible to specify the following GridSpec, which seems to (almost) give my desired results in a hacky way:
gs = GridSpec(2, 4, hspace=-0.5)
fig = plt.figure()
ax1 = fig.add_subplot(gs[:2, :2])
ax2 = fig.add_subplot(gs[0, 3])
output: