CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
groundhogday321

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

GitHub Repository: groundhogday321/python-ipywidgets
Path: blob/master/Python Add Interactivity to Jupyter Notebooks with ipywidgets.ipynb
Views: 87
Kernel: Python 3

Python Add Interactivity to Jupyter Notebooks with ipywidgets

GitHub Notebook

from IPython.display import IFrame documentation = IFrame(src='https://ipywidgets.readthedocs.io/en/latest/examples/Widget%20List.html', width=1000, height=400) display(documentation)
import ipywidgets # ; to hide output details

IntSlider

# IntSlider # square number slider = ipywidgets.IntSlider(value=5, min=0, max=10, step=1, description='Square:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='d') def square1(number): return number*number ipywidgets.interact(square1, number=slider);
# IntSlider with function # square number def square2(number): return number*number ipywidgets.interact(square2, number=(0,10));
# IntSlider with decorator # square number @ipywidgets.interact(number=(1,10)) def square3(number): return number*number

BoundedIntText

# make chart interactive # change number of bins for histogram import matplotlib.pyplot as plt %matplotlib inline from vega_datasets import data # data cars = data.cars() hist_data = cars['Miles_per_Gallon'].dropna() arrow = ipywidgets.BoundedIntText(value=50, min=25, max=100, step=1, description='Bins:', disabled=False) def create_histogram(bins): plt.hist(hist_data, bins=bins) ipywidgets.interact(create_histogram, bins=arrow);

Checkbox

# add map layers to cartopy map from ipywidgets import Layout import matplotlib.pyplot as plt import cartopy.crs as ccrs import cartopy.feature as cfeature land = ipywidgets.Checkbox(description='land', style={'description_width': 'initial'}) ocean = ipywidgets.Checkbox(description='ocean', style={'description_width': 'initial'}) coastline = ipywidgets.Checkbox(description='coastline', style={'description_width': 'initial'}) borders = ipywidgets.Checkbox(description='borders', style={'description_width': 'initial'}) lakes = ipywidgets.Checkbox(description='lakes', style={'description_width': 'initial'}) rivers = ipywidgets.Checkbox(description='rivers', style={'description_width': 'initial'}) plot_locations = ipywidgets.Checkbox(description='plot_locations', style={'description_width': 'initial'}) box_layout = ipywidgets.Layout(display='inline-flex', flex_flow='row', align_items='stretch', border='solid', width='100%') ui = ipywidgets.HBox([land, ocean, coastline, borders, lakes, rivers, plot_locations], layout=box_layout) def create_map(land,ocean,coastline,borders,lakes,rivers,plot_locations): data_crs = ccrs.PlateCarree() fig = plt.figure(figsize=(12, 8)) ax = fig.add_subplot(1, 1, 1, projection=data_crs) # make the map global rather than have it zoom in to the extents of any plotted data ax.set_global() if land == True: ax.add_feature(cfeature.LAND) if ocean == True: ax.add_feature(cfeature.OCEAN) if coastline == True: ax.add_feature(cfeature.COASTLINE) if borders == True: ax.add_feature(cfeature.BORDERS, linestyle=':') if lakes == True: ax.add_feature(cfeature.LAKES, alpha=0.5) if rivers == True: ax.add_feature(cfeature.RIVERS) if plot_locations == True: ny_lon, ny_lat = -75, 43 delhi_lon, delhi_lat = 77.23, 28.61 ax.plot(ny_lon, ny_lat, 'o', transform=data_crs) ax.plot(delhi_lon, delhi_lat, 'o', transform=data_crs) ax.text(ny_lon - 2, ny_lat - 4, 'New York', horizontalalignment='right', transform=data_crs) ax.text(delhi_lon + 1, delhi_lat - 6, 'Delhi', horizontalalignment='left', transform=data_crs) out = ipywidgets.interactive_output(create_map, {'land': land, 'ocean': ocean, 'coastline': coastline, 'borders': borders, 'lakes': lakes, 'rivers': rivers, 'plot_locations': plot_locations}) display(ui, out)

Dropdown

# generate password drop_down = ipywidgets.Dropdown(options=list(range(8,21)), value=8, description='Number:', disabled=False) def generate_password(length): import string import random password_choices = string.ascii_letters+'123456789'+'!@#$%^&*' password = [random.choice(password_choices) for _ in range(length)] return ''.join(password) ipywidgets.interact(generate_password, length=drop_down);

Text

# take user input text = ipywidgets.Text(value='', placeholder='type here', description='String:', disabled=False) instructions = ipywidgets.widgets.HTML('Enter your name:') display(instructions) display(text) def submit(greeting): print('Hello {}'.format(text.value)) text.on_submit(submit)
Hello Bob

Link Widgets

# link widgets together a = ipywidgets.widgets.FloatText() b = ipywidgets.widgets.FloatLogSlider() display(a,b) link_widgets = ipywidgets.link((a, 'value'), (b, 'value'))
# ipywidgets.link?

Interact Manual

# choose from list at random import random @ipywidgets.interact_manual() def random_choice(): l = list('abcdefghijklmnopqrstuvwxyz') print(random.choice(l))
# randomly change color of image import random from PIL import Image @ipywidgets.interact_manual() def random_choice(): flower = Image.open('path/img.jpg') r, g, b = flower.split() x = random.choice([r, g, b]) y = random.choice([r, g, b]) z = random.choice([r, g, b]) flower_color = Image.merge('RGB', (x, y, z)) flower_color.show()