Exercise: Dash Graph Components

Practice with some lab exercises.

We'll cover the following

Exercise 1

Create a Dash app that has an HTML header 1 component as well as a subplot with a single row and two columns. In row 1, column 1, create a bar plot that looks at the average daily rate of employees for each department. For row 1, column 2, create a bar plot with the average daily rate of employees for each field of education (EducationField) in the dataset. Use the BOOTSTRAP external stylesheet to make the app more visually appealing than the default settings.

Solution

  • The below code defines a function get_avg_daily_rate() on line 1 that takes a pandas DataFrame and a column name as input and returns a new DataFrame with two columns: the grouping variable and the mean daily rate.

  • A new subplot is created using the make_subplots() function on line 15 from Plotly. This subplot has two columns and shares the y-axis. The subplot titles are DailyRate Average by Department and DailyRate Average by EducationField.

  • The function get_avg_daily_rate() on lines 20 and 21 respectively is used to get the data for each subplot, which is then used to create a Plotly bar trace for each subplot.

  • The two traces are added to the subplot using the add_trace() method on lines 26 and 27 of the fig object.

  • A new JupyterDash app is created on line 30 using the JupyterDash function and the Bootstrap theme.

  • The app layout is set using the html.Div method on line 33 which includes an html.H1 element and a dcc.Graph element containing the fig object.

Get hands-on with 1200+ tech skills courses.