Here is a MWE:
import numpy as np
import matplotlib.pyplot as plt
def hamilton(x, p):
return p**2 + x**4 - x**2 + x/7
def get_random_matrix(x, y):
return np.random.uniform(size=x*y).reshape((x, y))
def update(event, ax, contour, image, x_num, p_num):
mode = event.canvas.toolbar.mode
if mode == '' and event.inaxes and event.button == 1:
fig = plt.gcf()
for i in range(20):
mat = get_random_matrix(x_num, p_num)
image.set_data(mat)
fig.canvas.draw()
fig.canvas.flush_events()
def update_blit(event, ax, contour, image, x_num, p_num):
mode = event.canvas.toolbar.mode
if mode == '' and event.inaxes and event.button == 3:
fig = plt.gcf()
bg = fig.canvas.copy_from_bbox(fig.bbox)
fig.canvas.blit(fig.bbox)
for i in range(20):
fig.canvas.restore_region(bg)
mat = get_random_matrix(x_num, p_num)
image.set_data(mat)
ax.draw_artist(image)
fig.canvas.blit(fig.bbox)
fig.canvas.flush_events()
x_max = 2
p_max = 2
x_num = 100
p_num = 100
x_1d = np.linspace(-x_max, x_max, x_num)
p_1d = np.linspace(-p_max, p_max, p_num)
x_2d, p_2d = np.meshgrid(x_1d, p_1d)
fig, ax = plt.subplots()
ax.axis([x_1d[0], x_1d[-1], p_1d[0], p_1d[-1]])
contour = ax.contour(x_2d, p_2d, hamilton(x_2d, p_2d), zorder=100)
mat = get_random_matrix(x_num, p_num)
image = ax.imshow(mat, cmap="Grays", extent=ax.axis())
fig.canvas.mpl_connect("button_press_event", lambda event: update(
event, ax, contour, image, x_num, p_num)
)
fig.canvas.mpl_connect("button_press_event", lambda event: update_blit(
event, ax, contour, image, x_num, p_num)
)
Left-clicking generates 20 random matrices that are plotted with imshow, and importantly the contour lines stay visible. Right-clicking does the same, but using blit (which I want for performance in a more demanding setting).
Now, this works fine, but the contour vanishes. I don’t really understand why that is, am I not including the contour in the background that gets restored? I tried setting an explicit zorder
, but that didn’t help.
I also tried using FuncAnimation
instead, but that yielded the same behaviour.
Interestingly, the contour reappears after e.g. resizing the plot window (Qt5Agg, Matplotlib 3.9.0, Python 3.11, Linux).
Noctis is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.