Exercise: The Dash Architecture
Practice with some lab exercises.
We'll cover the following
Exercise 1
Create a Dash app with a dataset of your choice with an HTML header 1 component with the text “My App.” Add a Plotly visual of your choice and place a paragraph below the image saying “Thanks for viewing my app.”
Solution
This code creates a simple web application using Dash, Plotly, and JupyterDash to display a scatter plot based on a dataset of top YouTubers. Here’s a breakdown of the main sections:
-
Load dataset and generate scatter plot:
- Load a CSV file called
top_youtubers.csv
on line 2 using pandas and store it in a DataFrame calleddf
. - Create a scatter plot using Plotly Express with
video_views_1000s
on line 3 on the x-axis,subscribers_1000s
on the y-axis, and black markers. - Update the scatter plot’s layout on line 4, setting the title and centering it.
- Update the marker size to
5
on line 5.
- Load a CSV file called
-
Dash app:
- Initialize a JupyterDash app named
app
, on line 8. - Define the layout of the app using
html.Div
on line 11, which (as a reminder) is a Dash HTML component representing adiv
in HTML. Inside thehtml.Div
component, three child elements are added:html.H1
: This creates an H1 header on line 12 with the textMy App
. Theid
attribute is set tomy-header
, which can be used for targeting this element with CSS or JavaScript.dcc.Graph
: This is a Dash Core Component (dcc) on line 13 representing a Plotly chart. Thefigure
attribute is set to the previously created scatter plot (fig
). Theid
attribute is set tomy-scatter
, which can be used for targeting this element with CSS or JavaScript.html.P
: This creates a paragraph with the textThanks for visiting my app
on line 14. Theid
attribute is set tomy-message
, which can be used for targeting this element with CSS or JavaScript.
- Initialize a JupyterDash app named
-
Run the app:
- The layout of the app is a hierarchical structure of components that defines the appearance of the app. The components used in the layout are from two main libraries: Dash HTML Components (e.g.,
html.Div
,html.H1
,html.P
) and Dash Core Components (e.g.,dcc.Graph
). These components are used to generate the HTML and JavaScript that will be served to the user’s web browser, allowing for an interactive and responsive user interface.
- The layout of the app is a hierarchical structure of components that defines the appearance of the app. The components used in the layout are from two main libraries: Dash HTML Components (e.g.,
Get hands-on with 1400+ tech skills courses.