Gottit.
I'm working in VSCode, and I needed this to render plots to a standalone window (otherwise I can't get 'interactive' -- if anyone can achieve inline-interactive in VSCode, please comment):
%matplotlib
First make a couple of plots:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax1 = plt.subplot(2, 1, 1) ; line1, = ax1.plot(range(5))
ax2 = plt.subplot(2, 1, 2) ; line2, = ax2.plot(range(5,-1,-1))
Now the hard part:
# Returns a new axis object which is inset into the passed `ax` axis
# centered at `x` (w.r.t. the axis' coord system)
def add_inset(ax, x):
X0, Y0, W, H = 0, 1, 2, 3 # for indexing rectangle objects
xmin, xmax = ax.get_xlim()
x01 = (x-xmin)/(xmax-xmin)
w = 0.2 # overlay should be 20% the width of the axis
ロoverlay_in_ax = [x01-w/2, 0.1, w, 0.8] # rect for overlay within ax (values 0 to 1)
overlay_absolute_origin_px = ax.transAxes.transform(
(ロoverlay_in_ax[X0], ロoverlay_in_ax[Y0]))
overlay_absolute_origin = ax.figure.transFigure.inverted(
).transform(overlay_absolute_origin_px)
ロax_in_fig = ax.get_position() # box of axis within figure (values 0 to 1)
ロoverlay_in_fig = [
overlay_absolute_origin[X0],
overlay_absolute_origin[Y0],
ロax_in_fig.width * ロoverlay_in_ax[W],
ロax_in_fig.height * ロoverlay_in_ax[H]
]
return fig.add_axes(ロoverlay_in_fig)
def on_down(event):
on_click(event, 'down')
def on_up(event):
on_click(event, 'up')
ax_inset = None
def on_click(event, updown):
x, y = event.xdata, event.ydata
ax = event.inaxes
print(updown, x, y, ax, ax==ax1, ax==ax2)
print(event.x, event.y)
if updown == 'down':
line2.set_color('red')
global ax_inset
ax_inset = add_inset(ax, x)
ax_inset.plot([1]*5)
else:
print('off')
ax_inset.remove()
fig.canvas.draw_idle() # was .draw(), recommended by gitter people
plt.connect('button_press_event', on_down)
plt.connect('button_release_event', on_up)
Here's the result:

Resources:
https://github.com/matplotlib/interactive_tutorial <- tutorial #6 covers 'interactive'
How to make matplotlib.pyplot subplots that overlap?
https://github.com/matplotlib/matplotlib/blob/c06e8709dde6504d396349c0c80ef019c88c3927/lib/matplotlib/backends/web_backend/nbagg_uat.ipynb
https://matplotlib.org/stable/users/interactive.html <-- recommends %matplotlib
which works, even tho' it's not inline
Matplotlib coordinates tranformation