Python Matplotlib:使用小部件以交互方式更改显示的图形 [英] Python Matplotlib: change the displayed figure interactively using a widget
问题描述
我有一个数据列表,例如 {A_1, A_2, A_3, ...},其中每个元素又是一个大数据列表,例如 A_i = {p_i_1, p_i_2, ...}.
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, ...}.
我想使用 Matplotlib 制作每个 A_i 的列表图,比如 plot_A_i,然后有一个功能来更改 plot_A_i 之间的显示图.因为每个A_i都很大,所以我不想每次都重新绘制它,而是先绘制所有图,然后使用Matplotlib的某种小部件更改显示的图.我想到的是像Mathematica的操纵"之类的东西.我该怎么做?
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?
推荐答案
这是我如何使用 Axes.set_visible() 做到的.任何意见和/或建议都将受到欢迎!
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()
这篇关于Python Matplotlib:使用小部件以交互方式更改显示的图形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!