Skip to main content
Query

Jupyter_Widgets

  • Page ID
    164137
  •  

    Matplotlib

    %matplotlib widget
    
    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.animation as animation
    
    # Fixing random state for reproducibility
    np.random.seed(19680801)
    
    
    def gen_rand_line(length, dims=2):
        """
        Create a line using a random walk algorithm.
    
        Parameters
        ----------
        length : int
            The number of points of the line.
        dims : int
            The number of dimensions of the line.
        """
        line_data = np.empty((dims, length))
        line_data[:, 0] = np.random.rand(dims)
        for index in range(1, length):
            # scaling the random numbers by 0.1 so
            # movement is small compared to position.
            # subtraction by 0.5 is to change the range to [-0.5, 0.5]
            # to allow a line to move backwards.
            step = (np.random.rand(dims) - 0.5) * 0.1
            line_data[:, index] = line_data[:, index - 1] + step
        return line_data
    
    
    def update_lines(num, data_lines, lines):
        for line, data in zip(lines, data_lines):
            # NOTE: there is no .set_data() for 3 dim data...
            line.set_data(data[0:2, :num])
            line.set_3d_properties(data[2, :num])
        return lines
    
    
    # Attaching 3D axis to the figure
    fig = plt.figure()
    ax = fig.add_subplot(projection="3d")
    
    # Fifty lines of random 3-D lines
    data = [gen_rand_line(25, 3) for index in range(50)]
    
    # Creating fifty line objects.
    # NOTE: Can't pass empty arrays into 3d version of plot()
    lines = [ax.plot(dat[0, 0:1], dat[1, 0:1], dat[2, 0:1])[0] for dat in data]
    
    # Setting the axes properties
    ax.set_xlim3d([0.0, 1.0])
    ax.set_xlabel('X')
    
    ax.set_ylim3d([0.0, 1.0])
    ax.set_ylabel('Y')
    
    ax.set_zlim3d([0.0, 1.0])
    ax.set_zlabel('Z')
    
    ax.set_title('3D Test')
    
    # Creating the Animation object
    line_ani = animation.FuncAnimation(
        fig, update_lines, 50, fargs=(data, lines), interval=50)
    
    plt.show()

    Bqplot

    import numpy as np
    from bqplot import pyplot as plt
    
    size = 100
    np.random.seed(0)
    x_data = np.arange(size)
    y_data = np.cumsum(np.random.randn(size)  * 100.0)
    
    plt.figure(title='My First Plot')
    plt.plot(x_data, y_data)
    plt.show()

    Plotly

    import plotly.express as px
    df = px.data.tips()
    fig = px.histogram(df, x="total_bill", y="tip", color="sex", marginal="rug",
                       hover_data=df.columns)
    fig.show()

    Ipyvolume

    import numpy as np
    import ipyvolume as ipv
    V = np.zeros((128,128,128)) # our 3d array
    # outer box
    V[30:-30,30:-30,30:-30] = 0.75
    V[35:-35,35:-35,35:-35] = 0.0
    # inner box
    V[50:-50,50:-50,50:-50] = 0.25
    V[55:-55,55:-55,55:-55] = 0.0
    ipv.quickvolshow(V, level=[0.25, 0.75], opacity=0.03, level_width=0.1, data_min=0, data_max=1)

    nglview

    import nglview as nv
    
    view = nv.show_structure_file(nv.datafiles.PDB)
    view

    Ipytcytoscape

    import ipycytoscape
    data = {
      'nodes': [
          { 'data': { 'id': 'desktop', 'name': 'Cytoscape', 'href': 'http://cytoscape.org' } },
          { 'data': { 'id': 'a', 'name': 'Grid', 'href': 'http://cytoscape.org' } },
          { 'data': { 'id': 'b', 'name': 'Cola', 'href': 'http://cytoscape.org' } },
          { 'data': { 'id': 'c', 'name': 'Popper', 'href': 'http://cytoscape.org' } },
          { 'data': { 'id': 'js', 'name': 'Cytoscape.js', 'href': 'http://js.cytoscape.org' } }
      ],
      'edges': [
          {'data': { 'source': 'desktop', 'target': 'js' }},
          {'data': { 'source': 'a', 'target': 'b' }},
          {'data': { 'source': 'a', 'target': 'c' }},
          {'data': { 'source': 'b', 'target': 'c' }},
          {'data': { 'source': 'js', 'target': 'b' }}
      ]
    }
    cytoscapeobj = ipycytoscape.CytoscapeWidget()
    cytoscapeobj.graph.add_graph_from_json(data)
    cytoscapeobj.set_style([{
      'selector': 'node',
      'css': {
          'content': 'data(name)',
          'text-valign': 'center',
          'color': 'white',
          'text-outline-width': 2,
          'text-outline-color': 'green',
          'background-color': 'green'
      }
      },
      {
      'selector': ':selected',
      'css': {
          'background-color': 'black',
          'line-color': 'black',
          'target-arrow-color': 'black',
          'source-arrow-color': 'black',
          'text-outline-color': 'black'
      }}
      ])
    cytoscapeobj

    Pythreejs

    from pythreejs import *
    from IPython.display import display
    import ipywidgets
    # Reduce repo churn for examples with embedded state:
    from pythreejs._example_helper import use_example_model_ids
    use_example_model_ids()
    
    ball = Mesh(geometry=SphereGeometry(),
                material=MeshLambertMaterial(color='red'))
    key_light = DirectionalLight(color='white', position=[3, 5, 1], intensity=0.5)
    
    c = PerspectiveCamera(position=[0, 5, 5], up=[0, 1, 0], children=[key_light])
    
    scene = Scene(children=[ball, c, AmbientLight(color='#777777')], background=None)
    
    renderer = Renderer(camera=c,
                        scene=scene,
                        alpha=True,
                        clearOpacity=0,
                        controls=[OrbitControls(controlling=c)])
    display(renderer)
    from pythreejs import *
    import ipywidgets
    from IPython.display import display
    # Reduce repo churn for examples with embedded state:
    from pythreejs._example_helper import use_example_model_ids
    use_example_model_ids()
    view_width = 600
    view_height = 400
    
    
    sphere = Mesh(
        SphereBufferGeometry(1, 32, 16),
        MeshStandardMaterial(color='red')
    )
    
    cube = Mesh(
        BoxBufferGeometry(1, 1, 1),
        MeshPhysicalMaterial(color='green'),
        position=[2, 0, 4]
    )
    
    camera = PerspectiveCamera( position=[10, 6, 10], aspect=view_width/view_height)
    key_light = DirectionalLight(position=[0, 10, 10])
    ambient_light = AmbientLight()
    
    positon_track = VectorKeyframeTrack(name='.position',
        times=[0, 2, 5],
        values=[10, 6, 10,
                6.3, 3.78, 6.3,
                -2.98, 0.84, 9.2,
               ])
    rotation_track = QuaternionKeyframeTrack(name='.quaternion',
        times=[0, 2, 5],
        values=[-0.184, 0.375, 0.0762, 0.905,
                -0.184, 0.375, 0.0762, 0.905,
                -0.0430, -0.156, -0.00681, 0.987,
               ])
    
    camera_clip = AnimationClip(tracks=[positon_track, rotation_track])
    camera_action = AnimationAction(AnimationMixer(camera), camera_clip, camera)
    
    scene = Scene(children=[sphere, cube, camera, key_light, ambient_light])
    controller = OrbitControls(controlling=camera)
    renderer = Renderer(camera=camera, scene=scene, controls=[controller],
                        width=view_width, height=view_height)
    
    renderer

     

    camera_action

     

    from pythreejs import *
    from IPython.display import display
          
    # Materials
    mat = MeshStandardMaterial(color='#ff0000')
    mat_green = MeshStandardMaterial(color='#00ff00')
    mat_blue = MeshStandardMaterial(color='#0000ff')
          
    # Geometries
    torus = TorusGeometry(radius=12, tube=3, radialSegments=16, tubularSegments=100)
    sphere = SphereGeometry(radius=12, _flat=True)
          
    bufferSphere = SphereBufferGeometry(radius=12, _flat=True)
    bufferTorus = TorusBufferGeometry(radius=12, tube=3, radialSegments=16, tubularSegments=100)
          
    sphere
    bufferSphere

    Ipyleaflet

    from ipyleaflet import Map, TileLayer, basemaps
    from ipyleaflet.velocity import Velocity
    import xarray as xr
    import os
    
    if not os.path.exists('wind-global.nc'):
      url = 'https://github.com/benbovy/xvelmap/raw/master/notebooks/wind-global.nc'
      import requests
      r = requests.get(url)
      wind_data = r.content
      with open('wind-global.nc', 'wb') as f:
          f.write(wind_data)
    
    center = [0, 0]
    zoom = 1
    m = Map(center=center, zoom=zoom, interpolation='nearest', basemap=basemaps.CartoDB.DarkMatter)
    
    ds = xr.open_dataset('wind-global.nc')
    display_options = {
        'velocityType': 'Global Wind',
        'displayPosition': 'bottomleft',
        'displayEmptyString': 'No wind data'
    }
    wind = Velocity(data=ds,
                    zonal_speed='u_wind',
                    meridional_speed='v_wind',
                    latitude_dimension='lat',
                    longitude_dimension='lon',
                    velocity_scale=0.01,
                    max_velocity=20,
                    display_options=display_options)
    m.add_layer(wind)
    
    m

    Pandas

    import pandas as pd
    iris = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv')
    iris

    bqplot

    #You can scroll this code!
    import pandas as pd
    import numpy as np
    import os
    
    from bqplot import (
        LogScale, LinearScale, OrdinalColorScale, ColorAxis,
        Axis, Scatter, Lines, CATEGORY10, Label, Figure, Tooltip
    )
    
    from ipywidgets import HBox, VBox, IntSlider, Play, jslink
    initial_year = 1800
    data = pd.read_json('https://raw.githubusercontent.com/bqplot/bqplot/958b0679cbccbc1411688cc6f8a5a22642377c68/examples/Applications/Wealth%20Of%20Nations/nations.json')
    def clean_data(data):
        for column in ['income', 'lifeExpectancy', 'population']:
            data = data.drop(data[data[column].apply(len) <= 4].index)
        return data
    
    def extrap_interp(data):
        data = np.array(data)
        x_range = np.arange(1800, 2009, 1.)
        y_range = np.interp(x_range, data[:, 0], data[:, 1])
        return y_range
    
    def extrap_data(data):
        for column in ['income', 'lifeExpectancy', 'population']:
            data[column] = data[column].apply(extrap_interp)
        return data
    data = clean_data(data)
    data = extrap_data(data)
    income_min, income_max = np.min(data['income'].apply(np.min)), np.max(data['income'].apply(np.max))
    life_exp_min, life_exp_max = np.min(data['lifeExpectancy'].apply(np.min)), np.max(data['lifeExpectancy'].apply(np.max))
    pop_min, pop_max = np.min(data['population'].apply(np.min)), np.max(data['population'].apply(np.max))
    def get_data(year):
        year_index = year - 1800
        income = data['income'].apply(lambda x: x[year_index])
        life_exp = data['lifeExpectancy'].apply(lambda x: x[year_index])
        pop =  data['population'].apply(lambda x: x[year_index])
        return income, life_exp, pop
    tt = Tooltip(fields=['name', 'x', 'y'], labels=['Country Name', 'Income per Capita', 'Life Expectancy'])
    year_label = Label(x=[0.75], y=[0.10], default_size=46, font_weight='bolder', colors=['orange'],
                       text=[str(initial_year)], enable_move=True)
    x_sc = LogScale(min=income_min, max=income_max)
    y_sc = LinearScale(min=life_exp_min, max=life_exp_max)
    c_sc = OrdinalColorScale(domain=data['region'].unique().tolist(), colors=CATEGORY10[:6])
    size_sc = LinearScale(min=pop_min, max=pop_max)
    ax_y = Axis(label='Life Expectancy', scale=y_sc, orientation='vertical', side='left', grid_lines='solid')
    ax_x = Axis(label='Income per Capita', scale=x_sc, grid_lines='solid')
    # Start with the first year's data
    cap_income, life_exp, pop = get_data(initial_year)
    wealth_scat = Scatter(x=cap_income, y=life_exp, color=data['region'], size=pop,
                          names=data['name'], display_names=False,
                          scales={'x': x_sc, 'y': y_sc, 'color': c_sc, 'size': size_sc},
                          default_size=4112, tooltip=tt, animate=True, stroke='Black',
                          unhovered_style={'opacity': 0.5})
    nation_line = Lines(x=data['income'][0], y=data['lifeExpectancy'][0], colors=['Gray'],
                           scales={'x': x_sc, 'y': y_sc}, visible=False)
    time_interval = 10
    fig = Figure(marks=[wealth_scat, year_label, nation_line], axes=[ax_x, ax_y],
                 title='Health and Wealth of Nations', animation_duration=time_interval)
    year_slider = IntSlider(min=1800, max=2008, step=1, description='Year', value=initial_year)
    def hover_changed(change):
        if change.new is not None:
            nation_line.x = data[data['name'] == wealth_scat.names[change.new]]['income'].values[0]
            nation_line.y = data[data['name'] == wealth_scat.names[change.new]]['lifeExpectancy'].values[0]
            nation_line.visible = True
        else:
            nation_line.visible = False
            
    wealth_scat.observe(hover_changed, 'hovered_point')
    def year_changed(change):
        wealth_scat.x, wealth_scat.y, wealth_scat.size = get_data(year_slider.value)
        year_label.text = [str(year_slider.value)]
    
    year_slider.observe(year_changed, 'value')
    play_button = Play(min=1800, max=2008, interval=time_interval)
    jslink((play_button, 'value'), (year_slider, 'value'))
    VBox([HBox([play_button, year_slider]), fig])

    Bokeh

    import numpy as np
    from scipy.integrate import odeint
    
    from bokeh.plotting import figure, output_file, show
    
    sigma = 10
    rho = 28
    beta = 8.0/3
    theta = 3 * np.pi / 4
    
    def lorenz(xyz, t):
        x, y, z = xyz
        x_dot = sigma * (y - x)
        y_dot = x * rho - x * z - y
        z_dot = x * y - beta* z
        return [x_dot, y_dot, z_dot]
    
    initial = (-10, -7, 35)
    t = np.arange(0, 100, 0.006)
    
    solution = odeint(lorenz, initial, t)
    
    x = solution[:, 0]
    y = solution[:, 1]
    z = solution[:, 2]
    xprime = np.cos(theta) * x - np.sin(theta) * y
    
    colors = ["#C6DBEF", "#9ECAE1", "#6BAED6", "#4292C6", "#2171B5", "#08519C", "#08306B",]
    
    p = figure(title="Lorenz attractor example", background_fill_color="#fafafa")
    
    p.multi_line(np.array_split(xprime, 7), np.array_split(z, 7),
                 line_color=colors, line_alpha=0.8, line_width=1.5)
    
    output_file("lorenz.html", title="lorenz.py example")
    
    show(p)