Commit 695452b6 authored by torradeflot's avatar torradeflot
Browse files

Add Plotly.Dash notebook

parents
Loading
Loading
Loading
Loading
+279 −0
Original line number Diff line number Diff line
%% Cell type:markdown id:35041541-936e-40a3-840e-b368a22cdd80 tags:

# Initial setup

%% Cell type:code id:41618d18-1a4b-477f-9a8f-5ff481cd01be tags:

``` python
from IPython.utils import io
import getpass

from dash import Dash
```

%% Cell type:code id:59450a26-d345-4a2a-88b6-f709155351bb tags:

``` python
USER = getpass.getuser()
PORT = 8050
PROXY_PATH = f'/user/{USER}/proxy/{PORT}/'

class PicDash(Dash):

    def __init__(self, *args, **kwargs):

        kwargs['requests_pathname_prefix'] = PROXY_PATH
        super().__init__(*args, **kwargs)

    def run(self, *args, **kwargs):

        kwargs['port'] = PORT
        with io.capture_output() as captured:
            super().run(*args, **kwargs)

        print(captured.stdout.replace(f'http://127.0.0.1:{PORT}', 'https://jupyter.pic.es'))
```

%% Cell type:markdown id:dcb5f708-c98b-40e0-8485-c4be9ec93c8c tags:

# Plotly charts in Dash

https://plotly.com/python/getting-started/

%% Cell type:code id:a3e83afd-7b18-40ea-88c1-8b0429931b9d tags:

``` python
from dash import Dash, dcc, html, Input, Output
import plotly.graph_objects as go
```

%% Cell type:code id:df5ab9e2-7b2b-43c8-9d4e-20b7fcbaf26b tags:

``` python
app = PicDash(__name__)
```

%% Cell type:code id:2b81bf26-cd5b-4a4c-81bf-2fff93343142 tags:

``` python
app.layout = html.Div([
    html.H4('Interactive color selection with simple Dash example'),
    html.P("Select color:"),
    dcc.Dropdown(
        id="dropdown",
        options=['Gold', 'MediumTurquoise', 'LightGreen'],
        value='Gold',
        clearable=False,
    ),
    dcc.Graph(id="graph"),
])


@app.callback(
    Output("graph", "figure"),
    Input("dropdown", "value"))
def display_color(color):
    fig = go.Figure(
        data=go.Bar(y=[2, 3, 1], # replace with your own data source
                    marker_color=color))
    return fig
```

%% Cell type:code id:3b94357c-6c92-4bc2-9c04-67af908326b1 tags:

``` python
app.run(jupyter_mode='external')
```

%% Output

    Dash app running on https://jupyter.pic.es/user/torradeflot/proxy/8050/
    

%% Cell type:markdown id:71e0e9d2-73b5-4c93-b5dd-96f77907b3fb tags:

# Minimal Dash App

https://dash.plotly.com/minimal-app

%% Cell type:code id:1f931e38-a085-4e33-a262-37d1d20eefb6 tags:

``` python
from dash import Dash, html, dcc, callback, Output, Input
import plotly.express as px
import pandas as pd

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv')

app = PicDash()

app.layout = [
    html.H1(children='Title of Dash App', style={'textAlign':'center'}),
    dcc.Dropdown(df.country.unique(), 'Canada', id='dropdown-selection'),
    dcc.Graph(id='graph-content')
]

@callback(
    Output('graph-content', 'figure'),
    Input('dropdown-selection', 'value')
)
def update_graph(value):
    dff = df[df.country==value]
    return px.line(dff, x='year', y='pop')

app.run(debug=True, jupyter_mode='external')
```

%% Output

    Dash app running on https://jupyter.pic.es/user/torradeflot/proxy/8050/
    

%% Cell type:markdown id:8fc2654a-fb17-4068-b470-fd00c1a9446a tags:

# Dash in 20 Minutes

## Hello World

https://dash.plotly.com/tutorial

%% Cell type:code id:a69a9ada-0e9f-4037-9388-7c14ccabb4f1 tags:

``` python
from dash import Dash, html

app = Dash()

app.layout = [html.Div(children='Hello World')]

app.run(debug=True)
```

%% Output


%% Cell type:markdown id:f5b61927-7b73-4ac1-baac-2ab3ac53df6c tags:

## Connecting to Data

%% Cell type:code id:502d4c8d-677f-4e1d-9579-0c2e682342f3 tags:

``` python
# Import packages
from dash import Dash, html, dash_table
import pandas as pd

# Incorporate data
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder2007.csv')

# Initialize the app
app = Dash()

# App layout
app.layout = [
    html.Div(children='My First App with Data'),
    dash_table.DataTable(data=df.to_dict('records'), page_size=10)
]

# Run the app
app.run(debug=True)
```

%% Output


%% Cell type:markdown id:b29d501e-0240-4512-8fb3-07e547c9b99d tags:

## Visualizing Data

%% Cell type:code id:04c08a06-bcdd-4429-977f-552e85f521a5 tags:

``` python
# Import packages
from dash import Dash, html, dash_table, dcc
import pandas as pd
import plotly.express as px

# Incorporate data
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder2007.csv')

# Initialize the app
app = Dash()

# App layout
app.layout = [
    html.Div(children='My First App with Data and a Graph'),
    dash_table.DataTable(data=df.to_dict('records'), page_size=10),
    dcc.Graph(figure=px.histogram(df, x='continent', y='lifeExp', histfunc='avg'))
]

# Run the app
if __name__ == '__main__':
    app.run(debug=True)
```

%% Output


%% Cell type:markdown id:e718a500-170f-4e95-b123-b31861920122 tags:

## HTML and CSS

%% Cell type:code id:4e31696d-0a38-420e-bdb8-18994d9b8d8e tags:

``` python
# Import packages
from dash import Dash, html, dash_table, dcc, callback, Output, Input
import pandas as pd
import plotly.express as px

# Incorporate data
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder2007.csv')

# Initialize the app - incorporate css
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = Dash(external_stylesheets=external_stylesheets)

# App layout
app.layout = [
    html.Div(className='row', children='My First App with Data, Graph, and Controls',
             style={'textAlign': 'center', 'color': 'blue', 'fontSize': 30}),

    html.Div(className='row', children=[
        dcc.RadioItems(options=['pop', 'lifeExp', 'gdpPercap'],
                       value='lifeExp',
                       inline=True,
                       id='my-radio-buttons-final')
    ]),

    html.Div(className='row', children=[
        html.Div(className='six columns', children=[
            dash_table.DataTable(data=df.to_dict('records'), page_size=11, style_table={'overflowX': 'auto'})
        ]),
        html.Div(className='six columns', children=[
            dcc.Graph(figure={}, id='histo-chart-final')
        ])
    ])
]

# Add controls to build the interaction
@callback(
    Output(component_id='histo-chart-final', component_property='figure'),
    Input(component_id='my-radio-buttons-final', component_property='value')
)
def update_graph(col_chosen):
    fig = px.histogram(df, x='continent', y=col_chosen, histfunc='avg')
    return fig

# Run the app
if __name__ == '__main__':
    app.run(debug=True)
```

%% Output


%% Cell type:code id:613aa8e5-dc39-4539-8aeb-3c54ba1a48e2 tags:

``` python
```
+235 −0
Original line number Diff line number Diff line
# ---
# jupyter:
#   jupytext:
#     formats: ipynb,py:light
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.16.2
#   kernelspec:
#     display_name: Python 3 (ipykernel)
#     language: python
#     name: python3
# ---

# # Initial setup

# +
from IPython.utils import io
import getpass

from dash import Dash

# +
USER = getpass.getuser()
PORT = 8050
PROXY_PATH = f'/user/{USER}/proxy/{PORT}/'

class PicDash(Dash):

    def __init__(self, *args, **kwargs):

        kwargs['requests_pathname_prefix'] = PROXY_PATH
        super().__init__(*args, **kwargs)

    def run(self, *args, **kwargs):

        kwargs['port'] = PORT
        with io.capture_output() as captured:
            super().run(*args, **kwargs)

        print(captured.stdout.replace(f'http://127.0.0.1:{PORT}', 'https://jupyter.pic.es'))


# -

# # Plotly charts in Dash
#
# https://plotly.com/python/getting-started/

from dash import Dash, dcc, html, Input, Output
import plotly.graph_objects as go


app = PicDash(__name__) 

# +
app.layout = html.Div([
    html.H4('Interactive color selection with simple Dash example'),
    html.P("Select color:"),
    dcc.Dropdown(
        id="dropdown",
        options=['Gold', 'MediumTurquoise', 'LightGreen'],
        value='Gold',
        clearable=False,
    ),
    dcc.Graph(id="graph"),
])


@app.callback(
    Output("graph", "figure"), 
    Input("dropdown", "value"))
def display_color(color):
    fig = go.Figure(
        data=go.Bar(y=[2, 3, 1], # replace with your own data source
                    marker_color=color))
    return fig


# -

app.run(jupyter_mode='external')

# # Minimal Dash App
#
# https://dash.plotly.com/minimal-app

# +
from dash import Dash, html, dcc, callback, Output, Input
import plotly.express as px
import pandas as pd

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv')

app = PicDash()

app.layout = [
    html.H1(children='Title of Dash App', style={'textAlign':'center'}),
    dcc.Dropdown(df.country.unique(), 'Canada', id='dropdown-selection'),
    dcc.Graph(id='graph-content')
]

@callback(
    Output('graph-content', 'figure'),
    Input('dropdown-selection', 'value')
)
def update_graph(value):
    dff = df[df.country==value]
    return px.line(dff, x='year', y='pop')

app.run(debug=True, jupyter_mode='external')

# -

# # Dash in 20 Minutes
#
# ## Hello World
#
# https://dash.plotly.com/tutorial

# +
from dash import Dash, html

app = Dash()

app.layout = [html.Div(children='Hello World')]

app.run(debug=True)
# -

# ## Connecting to Data

# +
# Import packages
from dash import Dash, html, dash_table
import pandas as pd

# Incorporate data
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder2007.csv')

# Initialize the app
app = Dash()

# App layout
app.layout = [
    html.Div(children='My First App with Data'),
    dash_table.DataTable(data=df.to_dict('records'), page_size=10)
]

# Run the app
app.run(debug=True)

# -

# ## Visualizing Data

# +
# Import packages
from dash import Dash, html, dash_table, dcc
import pandas as pd
import plotly.express as px

# Incorporate data
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder2007.csv')

# Initialize the app
app = Dash()

# App layout
app.layout = [
    html.Div(children='My First App with Data and a Graph'),
    dash_table.DataTable(data=df.to_dict('records'), page_size=10),
    dcc.Graph(figure=px.histogram(df, x='continent', y='lifeExp', histfunc='avg'))
]

# Run the app
if __name__ == '__main__':
    app.run(debug=True)

# -

# ## HTML and CSS

# +
# Import packages
from dash import Dash, html, dash_table, dcc, callback, Output, Input
import pandas as pd
import plotly.express as px

# Incorporate data
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder2007.csv')

# Initialize the app - incorporate css
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = Dash(external_stylesheets=external_stylesheets)

# App layout
app.layout = [
    html.Div(className='row', children='My First App with Data, Graph, and Controls',
             style={'textAlign': 'center', 'color': 'blue', 'fontSize': 30}),

    html.Div(className='row', children=[
        dcc.RadioItems(options=['pop', 'lifeExp', 'gdpPercap'],
                       value='lifeExp',
                       inline=True,
                       id='my-radio-buttons-final')
    ]),

    html.Div(className='row', children=[
        html.Div(className='six columns', children=[
            dash_table.DataTable(data=df.to_dict('records'), page_size=11, style_table={'overflowX': 'auto'})
        ]),
        html.Div(className='six columns', children=[
            dcc.Graph(figure={}, id='histo-chart-final')
        ])
    ])
]

# Add controls to build the interaction
@callback(
    Output(component_id='histo-chart-final', component_property='figure'),
    Input(component_id='my-radio-buttons-final', component_property='value')
)
def update_graph(col_chosen):
    fig = px.histogram(df, x='continent', y=col_chosen, histfunc='avg')
    return fig

# Run the app
if __name__ == '__main__':
    app.run(debug=True)

# -