简体   繁体   中英

Python Matplotlib: change the displayed figure interactively using a widget

I have a list of data, for example {A_1, A_2, A_3, ...}, where each element is again a big list of data, for example A_i = {p_i_1, p_i_2, ...}.

I want to use Matplotlib to make a list plot of each A_i, say plot_A_i, and then have a functionality to change the displayed plot among plot_A_i. Because each A_i is quite big, I don't want to redraw it every time, but first draw all the plots and then change the displayed one using some kind of widget of Matplotlib. What I have in mind is something like 'Manipulate' of Mathematica. How can I do that?

Here is how I did it using Axes.set_visible(). Any comment and/or suggestion will be more than welcome!

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider

def f(t):
    return np.exp(-t) * np.cos(2*np.pi*t)

class PlotList:
    def __init__(self, plots):
        self.cur_val = 0
        self.plots = plots
        self.plots[self.cur_val].set_visible(True)
    def set_visible(self, val):
        new_val = int(val)
        if(self.cur_val != new_val):
            self.plots[self.cur_val].set_visible(False)
            self.plots[new_val].set_visible(True)
            self.cur_val = new_val
        fig.canvas.draw_idle()

t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)


fig = plt.figure()
plot_axes_rect = [0.125, 0.15, .8, 0.75]
plots = [fig.add_axes(plot_axes_rect, label=1, visible=False),
         fig.add_axes(plot_axes_rect, label=2, visible=False)]
plots[0].plot(t1, f(t1), 'bo')
plots[1].plot(t2, f(t2), 'k')

pl = PlotList(plots)

theta_axes = fig.add_axes([0.125, 0.05, .8, 0.05])
theta_slider = Slider(theta_axes, 'theta', 0, 2,
                      valinit=pl.cur_val, valfmt='%d')

theta_slider.on_changed(pl.set_visible)

plt.show()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM