{"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"provenance":[],"toc_visible":true,"authorship_tag":"ABX9TyMQ8t6Lw9oA18jyu6gbFwfP"},"kernelspec":{"name":"python3","display_name":"Python 3"},"language_info":{"name":"python"}},"cells":[{"cell_type":"markdown","source":["# Dash\n","\n","
\"Dash is a productive Python framework for building web analytic applications. Written on top of Flask, Plotly.js, and React.js, Dash is ideal for building data visualization apps with highly custom user interfaces in pure Python.\"\n","\n","For those familiar with RStudio's [Shiny package](https://www.rstudio.com/products/shiny/) (designed to build interactive web applications from within the R/RStudio programming environment), `dash` was originally pitched as the equivalent package for Python\n","\n","For more background on `dash`:\n","- plotly, [\"Introducing Dash\"](https://medium.com/plotly/introducing-dash-5ecf7191b503) *Medium* (21 June 2017)\n","- Plotly, [\"PLOTCON 2016: Chris Parmer, Dash: Shiny for Python\"](https://youtu.be/5BAthiN0htc) *YouTube* (1 December 2016)\n","- `plotly`, [Dash Enterprise App Gallery](https://dash-gallery.plotly.host/Portal/)\n","- [Plotly, Dash GitHub repository](https://github.com/plotly/dash)\n"],"metadata":{"id":"ik_8OGlW0rdr"}},{"cell_type":"markdown","source":["## Setup & Environment\n","\n","To install `dash`:\n","- using `pip`: `pip install dash`\n","- in Jupyter notebook using `pip`: `pip install jupyter-dash`\n","- in Jupyter notebook using `conda`: `conda install -c conda-forge -c plotly jupyter-dash`\n","\n","The remainder of this tutorial focuses on `dash` outside the Jupyter notebook environment.\n","- For more on using `dash` in a notebook environment: plotly, [Jupyter-Dash Github Repository](https://github.com/plotly/jupyter-dash)"],"metadata":{"id":"T7AI8W411xdG"}},{"cell_type":"code","execution_count":1,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"HPbPb32E0pZM","executionInfo":{"status":"ok","timestamp":1706156359708,"user_tz":300,"elapsed":16728,"user":{"displayName":"Katherine Walden","userId":"17094108395123900917"}},"outputId":"81aee621-14db-42e3-a1d6-60ef5afc0d8d"},"outputs":[{"output_type":"stream","name":"stdout","text":["Collecting dash\n"," Downloading dash-2.14.2-py3-none-any.whl (10.2 MB)\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m10.2/10.2 MB\u001b[0m \u001b[31m14.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[?25hRequirement already satisfied: Flask<3.1,>=1.0.4 in /usr/local/lib/python3.10/dist-packages (from dash) (2.2.5)\n","Requirement already satisfied: Werkzeug<3.1 in /usr/local/lib/python3.10/dist-packages (from dash) (3.0.1)\n","Requirement already satisfied: plotly>=5.0.0 in /usr/local/lib/python3.10/dist-packages (from dash) (5.15.0)\n","Collecting dash-html-components==2.0.0 (from dash)\n"," Downloading dash_html_components-2.0.0-py3-none-any.whl (4.1 kB)\n","Collecting dash-core-components==2.0.0 (from dash)\n"," Downloading dash_core_components-2.0.0-py3-none-any.whl (3.8 kB)\n","Collecting dash-table==5.0.0 (from dash)\n"," Downloading dash_table-5.0.0-py3-none-any.whl (3.9 kB)\n","Requirement already satisfied: typing-extensions>=4.1.1 in /usr/local/lib/python3.10/dist-packages (from dash) (4.5.0)\n","Requirement already satisfied: requests in /usr/local/lib/python3.10/dist-packages (from dash) (2.31.0)\n","Collecting retrying (from dash)\n"," Downloading retrying-1.3.4-py3-none-any.whl (11 kB)\n","Collecting ansi2html (from dash)\n"," Downloading ansi2html-1.9.1-py3-none-any.whl (17 kB)\n","Requirement already satisfied: nest-asyncio in /usr/local/lib/python3.10/dist-packages (from dash) (1.6.0)\n","Requirement already satisfied: setuptools in /usr/local/lib/python3.10/dist-packages (from dash) (67.7.2)\n","Requirement already satisfied: importlib-metadata in /usr/local/lib/python3.10/dist-packages (from dash) (7.0.1)\n","Requirement already satisfied: Jinja2>=3.0 in /usr/local/lib/python3.10/dist-packages (from Flask<3.1,>=1.0.4->dash) (3.1.3)\n","Requirement already satisfied: itsdangerous>=2.0 in /usr/local/lib/python3.10/dist-packages (from Flask<3.1,>=1.0.4->dash) (2.1.2)\n","Requirement already satisfied: click>=8.0 in /usr/local/lib/python3.10/dist-packages (from Flask<3.1,>=1.0.4->dash) (8.1.7)\n","Requirement already satisfied: tenacity>=6.2.0 in /usr/local/lib/python3.10/dist-packages (from plotly>=5.0.0->dash) (8.2.3)\n","Requirement already satisfied: packaging in /usr/local/lib/python3.10/dist-packages (from plotly>=5.0.0->dash) (23.2)\n","Requirement already satisfied: MarkupSafe>=2.1.1 in /usr/local/lib/python3.10/dist-packages (from Werkzeug<3.1->dash) (2.1.4)\n","Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.10/dist-packages (from importlib-metadata->dash) (3.17.0)\n","Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.10/dist-packages (from requests->dash) (3.3.2)\n","Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.10/dist-packages (from requests->dash) (3.6)\n","Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.10/dist-packages (from requests->dash) (2.0.7)\n","Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.10/dist-packages (from requests->dash) (2023.11.17)\n","Requirement already satisfied: six>=1.7.0 in /usr/local/lib/python3.10/dist-packages (from retrying->dash) (1.16.0)\n","Installing collected packages: dash-table, dash-html-components, dash-core-components, retrying, ansi2html, dash\n","Successfully installed ansi2html-1.9.1 dash-2.14.2 dash-core-components-2.0.0 dash-html-components-2.0.0 dash-table-5.0.0 retrying-1.3.4\n"]}],"source":["!pip install dash # install dash"]},{"cell_type":"markdown","source":["## Basic `dash` Syntax\n","\n","`dash` apps include two main components.\n","- The app ***layout*** describes what the application looks like.\n","- The app ***interactivity*** describes the application's interactivity.\n","\n","The basic syntax for creating an application using `dash`:"],"metadata":{"id":"4NZ6lnu616z0"}},{"cell_type":"code","source":["# code for our figure; area chart with dropdown\n","df = px.data.gapminder() # load data\n","fig = px.area(df, x='year', y='pop') # create figure\n","df = px.data.gapminder() # load data\n","\n","# gets unique values from country column, creates a dictionary with Plotly parameters to generate dropdown options\n","country_options = [{'label': country, 'method': 'update', 'args':\n"," [{'y': [df[df['country'] == country]['pop']], 'x': [df[df['country'] == country]['year']]}]}\n"," for country in df['country'].unique()]\n","\n","fig.update_layout(updatemenus=[dict(type=\"dropdown\", buttons=country_options)]) # update menu with dropdown"],"metadata":{"id":"dThj6OHr3vNi"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["import plotly.express as px, dash # import statements\n","from dash import dcc, html\n","\n","app = dash.Dash() # create app\n","\n","# set app layout\n","app.layout = html.Div([\n"," dcc.Graph(figure=fig)\n","])\n","\n","app.run_server(debug=True, use_reloader=False) # run app"],"metadata":{"id":"hf-QRpRx2HST"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["## Customizing Your App\n","\n","We can start to customize a `dash` app by using an external style sheet. Similar to how we use CSS in combination with HTML, external style sheets can also be loaded and applied in `dash`"],"metadata":{"id":"RIrxMYw-3FzN"}},{"cell_type":"code","source":["import plotly.express as px, dash # import statements\n","from dash import dcc, html\n","\n","external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] # load style sheet; this example uses a URL; could also use local .css file\n","\n","app = dash.Dash(external_stylesheets=external_stylesheets) # create app\n","\n","# set app layout\n","app.layout = html.Div([\n"," dcc.Graph(figure=fig)\n","])\n","\n","app.run_server(debug=True, use_reloader=False) # run app"],"metadata":{"id":"ISk1e3TW3ORg"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["We can also start to modify components of the application by declaring HTML tags. Remember in HTML, tags like `
- plotly, \"Introduction to Dash\"
`, etc. are used for styling and formatting.\n","\n","The `dash_html_components` library has a component for every HTML tag. Let's modify our app layout to include a `H1` title, a `div` subtitle, and a `Graph` object."],"metadata":{"id":"FCqXmPdz3iGR"}},{"cell_type":"code","source":["import plotly.express as px, dash # import statements\n","from dash import dcc, html\n","\n","external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] # load style sheet; this example uses a URL; could also use local .css file\n","\n","app = dash.Dash(external_stylesheets=external_stylesheets) # create app\n","\n","# set app layout\n","app.layout = html.Div(children=[\n"," html.H1(children='Hello Dash'),\n","\n"," html.Div(children='''\n"," Dash: A web application framework for Python.\n"," '''),\n","\n"," dcc.Graph(\n"," id='example-graph',\n"," figure=fig\n"," )\n","])\n","\n","app.run_server(debug=True, use_reloader=False) # run app"],"metadata":{"id":"Xmlf4r2b3qby"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["### Additional Resources\n","\n","For more on the `dash_html_components` library: [`plotly`, Dash HTML Components](https://dash.plotly.com/dash-html-components)"],"metadata":{"id":"Y94l57OK6JZv"}},{"cell_type":"markdown","source":["## Interactivity\n","\n","As we saw with `plotly`, `dash` supports different kinds of user interaction.\n","\n","A quick example of a dropdown menu added to a `dash` app."],"metadata":{"id":"VKFwL-Ye4BU5"}},{"cell_type":"code","source":["from dash import dcc, html, Input, Output, callback\n","import plotly.express as px\n","\n","# we are using the restaurant tips dataset from Plotly Express\n","df = px.data.tips()\n","\n","external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] # load style sheet; this example uses a URL; could also use local .css file\n","\n","app = dash.Dash(external_stylesheets=external_stylesheets) # create app\n","\n","# specify the choices in the dropdown list, with default value\n","dropdown = dcc.Dropdown([\"Fri\", \"Sat\", \"Sun\"], \"Fri\", clearable=False)\n","\n","# create the chart component\n","graph = dcc.Graph()\n","\n","# layout of the app -- Heading 4 text followed by the dropdown list, followed by the chart\n","app.layout = html.Div([html.H4(\"Restaurant tips by day of week\"), dropdown, graph])\n","\n","# what output to get when you select an input\n","@callback(Output(graph, \"figure\"), Input(dropdown, \"value\"))\n","def update_bar_chart(day):\n"," mask = df[\"day\"] == day\n"," fig = px.bar(df[mask], x=\"sex\", y=\"total_bill\", color=\"smoker\", barmode=\"group\")\n"," return fig\n","\n","\n","if __name__ == \"__main__\":\n"," app.run_server(mode='external') # \"inline\" will output the dashboard in colab, \"external\" will output it in your browser via localhost"],"metadata":{"id":"zX8nV2YFG85G"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["### Additional Resources\n","\n","There's a lot more folks could explore in the `Dash` [core components](https://dash.plotly.com/dash-core-components) library.\n","\n","For more examples and documentation:\n","- [`dcc.RadioItems()`](https://dash.plotly.com/dash-core-components/radioitems)\n","- [`html.Button()`](https://dash.plotly.com/dash-html-components/button)\n","- [`dcc.DatePickerSingle()`](https://dash.plotly.com/dash-core-components/datepickersingle)\n","- [`dcc.DatePickerRange()`](https://dash.plotly.com/dash-core-components/datepickerrange)\n","- [`dcc.Upload()`](https://dash.plotly.com/dash-core-components/upload)\n","- [`dcc.Tabs()`](https://dash.plotly.com/dash-core-components/tabs)\n","- [`dcc.Graph()`](https://dash.plotly.com/dash-core-components/graph)"],"metadata":{"id":"YrRvIugr5eUG"}},{"cell_type":"markdown","source":["## Dash Resources\n","\n","We're just scratching the surface of what you can do using `dash`.\n","\n","To learn more, consult the [Dash User Guide](https://dash.plotly.com/). The [Dash Enterprise App Gallery](https://dash-gallery.plotly.host/Portal/) includes sample apps with the back-end `dash` code.\n","- See also: Daniel Barker, [\"A short Python tutorial using the open-source Plotly \"Dash\" library\"](https://towardsdatascience.com/a-short-python-tutorial-using-the-open-source-plotly-dash-library-part-i-e59fb1f1a457) *Towards Data Science* (24 April 2018).\n","\n","\n","\n"],"metadata":{"id":"gOqpbtjk6BAV"}}]}