Jupyter Notebook:带有小部件的交互式绘图 [英] Jupyter Notebook: interactive plot with widgets

查看:989
本文介绍了Jupyter Notebook:带有小部件的交互式绘图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试生成依赖于小部件的交互式图. 我遇到的问题是,当我使用滑块更改参数时,在前一个绘图之后进行了新绘图,相反,我期望仅一个绘图会根据参数进行更改.

I am trying to generate an interactive plot that depends on widgets. The problem I have is that when I change parameters using the slider, a new plot is done after the previous one, instead I would expect only one plot changing according to the parameters.

示例:

from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets

import matplotlib.pyplot as plt
%matplotlib inline

import numpy as np

def plot_func(freq):
    x = np.linspace(0, 2*np.pi)
    y = np.sin(x * freq)
    plt.plot(x, y)

interact(plot_func, freq = widgets.FloatSlider(value=7.5,
                                               min=1,
                                               max=5.0,
                                               step=0.5))

将滑块移动到4.0后,我有:

After moving the slider to 4.0, I have:

当我只希望一个数字随着移动滑块而改变时. 我该如何实现?

while I just want one figure to change as I move the slider. How can I achieve this?

(我正在使用Python 2.7,matplotlib 2.0,并且我刚刚将笔记本和jupyter更新为最新版本.请告知是否需要更多信息.)

(I am using Python 2.7, matplotlib 2.0 and I have just updated notebook and jupyter to the latest version. let me know if further info is needed.)

推荐答案

当您要更改图形而不是创建新图形时,我建议采用以下方法:

As you want to change the figure, instead of creating a new one, may I suggest the following way:

  1. 使用交互式后端; %matplotlib notebook
  2. 更新绘图中的线,而不是绘制新线.

所以代码看起来像这样:

So the code could look something like this:

%matplotlib notebook
from ipywidgets import *
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2 * np.pi)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
line, = ax.plot(x, np.sin(x))

def update(w = 1.0):
    line.set_ydata(np.sin(w * x))
    fig.canvas.draw_idle()

interact(update);

或者,您也可以像此答案中那样使用plt.show().

Alternatively you may use plt.show() as in this answer.

这篇关于Jupyter Notebook:带有小部件的交互式绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆