Exercise: The Dash Architecture

Practice with some lab exercises.

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:

  1. 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 called df.
    • 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.
  2. 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 a div in HTML. Inside the html.Div component, three child elements are added:
      • html.H1: This creates an H1 header on line 12 with the text My App. The id attribute is set to my-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. The figure attribute is set to the previously created scatter plot (fig). The id attribute is set to my-scatter, which can be used for targeting this element with CSS or JavaScript.
      • html.P: This creates a paragraph with the text Thanks for visiting my app on line 14. The id attribute is set to my-message, which can be used for targeting this element with CSS or JavaScript.
  3. 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.

Get hands-on with 1200+ tech skills courses.