如何在Jupyter笔记本中排列多个交互式图形?

时间:2020-08-10 15:50:38

标签: matplotlib jupyter-lab ipywidgets

我尝试使用ipywidget和matplotlib在jupyter笔记本中排列多个图形,但是它没有按我预期的那样工作...当我单独运行单元格时,它的运行正常,但是当我重新运行整个笔记本时,则没有任何显示。 您可以了解我的工作方式,并通过查找整个笔记本中的问题来帮助我。

单元格1

import ipywidgets as widgets
import numpy as np
import matplotlib.pyplot as plt

%matplotlib widget

pi = np.pi
t = np.linspace(0,2*pi,100)
fig1 = plt.figure(1,figsize=(6,2))
ax1 = fig1.add_subplot(1, 1, 1, aspect=1)

def update_plot(phase,amplitude):
    ax1.clear()
    ax1.plot(t,amplitude*np.sin(t+phase), color='r', label='Sinus')
    ax1.legend(loc=0)

phase = widgets.FloatSlider(min=-2,max=2,value=0,description='Phase:')
amplitude = widgets.FloatSlider(min=0,max=8,value=1.5,description='Amplitude:')
widgets.interactive(update_plot, phase=phase, amplitude=amplitude)

Cell2

fig2 = plt.figure(2,figsize=(6,2))
ax2 = fig2.add_subplot(1, 1, 1, aspect=1)
t2 = np.linspace(0,2*pi,100)

def update_plot(phase,amplitude):
    ax2.clear()
    ax2.plot(t2,amplitude*np.cos(t2+phase), color='b', label='Cosinus')
    ax2.legend(loc=0)

phase = widgets.FloatSlider(min=-2,max=2,value=0,description='Phase:')
amplitude = widgets.FloatSlider(min=0,max=8,value=1,description='Amplitude:')
widgets.interactive(update_plot, phase=phase, amplitude=amplitude)

整个笔记本

我不知道如何共享笔记本,所以我将ipynb文件粘贴到pastebin中。 https://pastebin.com/UdK4jzHK

1 个答案:

答案 0 :(得分:1)

要查看图,您只需添加 图。1 图2等在每个图形单元的末尾。
notebook example

PS:您随时可以在Collab上共享笔记本:https://colab.research.google.com/