Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
132 views
in Technique[技术] by (71.8m points)

python - widgets not getting displayed in ipywidgets

I am a beginner with jupyter notebooks and python. I tried the following (as advised in a youtube video - the sole teacher available for me).

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

The display of the plot is happening (of course without any curves - i did not create them), but the widget doesn't get displayed. Any help in this regard is welcome.

question from:https://stackoverflow.com/questions/65845531/widgets-not-getting-displayed-in-ipywidgets

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want to try Plotly instead of Matplotlib, use the following code instead:

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

In order to install Plotly and use it in your notebooks, please read this guide.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...