小部件未显示在 ipywidgets 中

时间:2021-01-22 12:49:50

标签: python jupyter-notebook ipywidgets

我是 jupyter notebooks 和 python 的初学者。我尝试了以下方法(按照 YouTube 视频中的建议 - 我唯一可以使用的老师)。

import ipywidgets as widgets
from IPython.display import display
import matplotlib.pyplot as plt
import numpy as np
%matplotlib nbagg 
x = np.linspace(0,2,1000)
fig,ax = plt.subplots(1,figsize =(10,4))

amp=widgets.FloatSlider(min=1,max=10,value=1,description='Amp:')
display(amp)
plt.suptitle('sine wave')
fig.show()

情节的显示正在发生(当然没有任何曲线 - 我没有创建它们),但没有显示小部件。欢迎在这方面提供任何帮助。

2 个答案:

答案 0 :(得分:1)

如果您想尝试 Plotly 而不是 Matplotlib,请改用以下代码:

import ipywidgets as widgets
from IPython.display import display
import plotly.graph_objs as go
import plotly.offline as py
import plotly.express as px
import numpy as np


# generate x values
x = np.linspace(0, 2 * np.pi, 100)
 
 
def my_sine(x, w, amp, phi):
    """
    Return a sine for x with angular frequeny w and amplitude amp.
    """
    return amp*np.sin(w * (x-phi))
 
 
@widgets.interact(w=(0, 10, 1), amp=(0, 4, .1), phi=(0, 2*np.pi+0.01, 0.01))
def view_image(w = 1.0, amp=1, phi=0):
    
    y = my_sine(x, w, amp, phi)
    
    fig = px.line(x=x, y=y)
    
    #Fix Y-axis range, otherwise the sine will appear to remain fixed, and only Y-axis values will change.
    fig.update_yaxes(range=(-4, 4))
    #Disable autosizing fo Figure canvas. Otherwise, every time a slider is moved, the canvas size will automatically change.
    fig.update_layout(autosize=False)
    
    fig.show()

为了安装 Plotly 并在您的笔记本中使用它,请阅读 this 指南。

答案 1 :(得分:0)

我认为在您的情况下不显示正弦波是正常的:您只创建了一个空的 Figure 和一个 Axesplt.subplots,并且您显示了一个滑块与任何绘图功能无关!

我建议使用以下代码来绘制具有不同交互属性的正弦波:

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

fig, ax = plt.subplots(figsize=(6, 4))
ax.set_ylim([-4, 4])
ax.grid(True)
 
# generate x values
x = np.linspace(0, 2 * np.pi, 100)
 
 
def my_sine(x, w, amp, phi):
    """
    Return a sine for x with angular frequeny w and amplitude amp.
    """
    return amp*np.sin(w * (x-phi))
 
 
@widgets.interact(w=(0, 10, 1), amp=(0, 4, .1), phi=(0, 2*np.pi+0.01, 0.01))
def update(w = 1.0, amp=1, phi=0):
    """Remove old lines from plot and plot new one"""
    [l.remove() for l in ax.lines]
    ax.plot(x, my_sine(x, w, amp, phi), color='C0')

魔术命令 %matplotlib widget 要求您安装 ipymplconda install -c conda-forge ipympl

我从一个非常好的tutorial那里获取了这段代码。

此代码仅适用于单个 Jupyter Notebook;为了在 Jupyter Lab 中使用它,需要安装一个扩展:jupyter labextension install jupyter-matplotlib

我目前也在学习如何使用 Jupyter 小部件来创建交互式笔记本!