Update only one subplot and not the entire figure (using matplotlib)
Asked Answered
A

1

8

I have a python script that provides a customized filter for zooming with matplotlib, to be used within a GUI. In particular, I have different subplots, and I would need to update ONLY the view of the subplot where I am zooming. If I use plt.draw(), it will update all the subplots of the figure. How can I target only the Artists related to the current subplot, in other words do something like ax.draw()?

Here is a simple example that illustrates the problem:

import matplotlib.pyplot as plt

#------------------------------------
# Definition of the initial figure
#------------------------------------

fig = plt.figure()

ax1 = fig.add_subplot(211)
ax1.plot([0,1],[0,1],'b-')
ax2 = fig.add_subplot(212)
ax2.plot([0,1],[0,1],'r-')

#------------------------------------
# Changing xlim in the 1st subplot with a click
#------------------------------------

def modify_subplot(event):
    ax1.set_xlim([0,0.5])
    plt.draw() # I want to replace this method with a
               # function that updates only the artists 
               # in ax1 without touching ax2

fig.canvas.mpl_connect('button_press_event', modify_subplot)

#------------------------------------
plt.show()

I tried to replace plt.draw() with ax1.draw(fig.canvas.get_renderer()) but it doesn't update anything.

Anfractuous answered 8/2, 2020 at 18:0 Comment(0)
E
0

As you said, you can do something like ax1.draw() but in the following way:

import matplotlib.pyplot as plt

fig = plt.figure()

ax1 = fig.add_subplot(211)
ax1.plot([0, 1], [0, 1], 'b-')
ax2 = fig.add_subplot(212)
ax2.plot([0, 1], [0, 1], 'r-')

def modify_subplot(event):
    # Change xlim of the first subplot
    ax1.set_xlim([0, 0.5])

    # Redraw only ax1
    fig.canvas.draw_idle()   
    ax1.draw_artist(ax1.patch)  # Clear the background of ax1
    for line in ax1.get_lines():
        ax1.draw_artist(line)  # Redraw all lines in ax1

    fig.canvas.blit(ax1.bbox)  # Update only the part of the figure corresponding to ax1

fig.canvas.mpl_connect('button_press_event', modify_subplot)

plt.show()
Edaphic answered 1/9, 2024 at 14:17 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.