Python Jupyter Notebook:带有小部件的交互式绘图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44329068/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:56:12  来源:igfitidea点击:

Jupyter Notebook: interactive plot with widgets

pythonmatplotlibjupyter-notebookjupyter

提问by FLab

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.

我正在尝试生成一个依赖于小部件的交互式绘图。我遇到的问题是,当我使用滑块更改参数时,会在前一个绘图之后完成一个新绘图,而不是我希望根据参数只更改一个绘图。

Example:

例子:

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))

After moving the slider to 4.0, I have:

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

enter image description here

在此处输入图片说明

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

而我只想在移动滑块时改变一个数字。我怎样才能做到这一点?

(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.)

(我使用的是 Python 2.7、matplotlib 2.0,我刚刚将 notebook 和 jupyter 更新到了最新版本。如果需要更多信息,请告诉我。)

回答by ImportanceOfBeingErnest

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

由于您想更改图形,而不是创建一个新图形,我可以建议以下方式:

  1. Use an interactive backend; %matplotlib notebook
  2. Update the line in the plot, instead of drawing new ones.
  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);

enter image description here

在此处输入图片说明

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

或者,您可以使用plt.show()as in this answer

回答by Stelios

This is an issue (?) introduced in the last version of jupyter and/or ipywidgets. One workaround I found was to add the line plt.show()at the end of plot_func.

这是 jupyter 和/或 ipywidgets 的最新版本中引入的问题 (?)。我发现的一种解决方法是plt.show()plot_func.