Can you "cache" matplotlib charts and show them dynamically?

I want to create several matplotlib plots in batch mode and then display them interactively, like something like this? (current code does not display graphics)

import matplotlib.pyplot as plt
from ipywidgets import interact
plots = {'a': plt.plot([1,1],[1,2]), 'b': plt.plot([2,2],[1,2])}

def f(x):
    return plots[x]

interact(f, x=['a','b'])  
+4
source share
1 answer

Redraw the shape

Perhaps you need something like this, where the figure is cleared of each new choice, and the artist in question is read on canvas.

%matplotlib notebook
import matplotlib.pyplot as plt
from ipywidgets import interact
plots = {'a': plt.plot([1,1],[1,2]), 'b': plt.plot([2,2],[1,2])}

def f(x):
    plt.gca().clear()
    plt.gca().add_artist(plots[x][0])
    plt.gca().autoscale()
    plt.gcf().canvas.draw_idle()

interact(f, x=['a','b']);

Result in jupyter laptop:

enter image description here

blitting

Unfortunately, the laptop backup does not currently support blitting . Using blitting, it was possible to build graphics in front of the songs, and then just break them down on the axis. It might look like this:

import matplotlib.pyplot as plt
from matplotlib.widgets import RadioButtons

fig, ax = plt.subplots()
fig.subplots_adjust(left=0.18)
line1, = ax.plot([1,1],[1,2])
line2, = ax.plot([2,2],[1,2], color="crimson")
line2.remove()
fig.canvas.draw()
# store state A, where line1 is present
stateA = fig.canvas.copy_from_bbox(ax.bbox)

line1.remove()
ax.add_artist(line2)
fig.canvas.draw()
# store state B, where line2 is present
stateB = fig.canvas.copy_from_bbox(ax.bbox)


plots = {'a': stateA, 'b': stateB}
rax = plt.axes([0.05, 0.4, 0.1, 0.15])
check = RadioButtons(rax, ('a', 'b'), (False, True))

def f(x):
    fig.canvas.restore_region(plots[x])

check.on_clicked(f)

plt.show()

. , matplotlib, RadioButtons interact .

+2

Source: https://habr.com/ru/post/1693216/


All Articles