Chapter 6: A dashboard fit for a CEO
This chapter introduces why executive metrics dashboards matter and previews building an interactive CEO KPI dashboard with Streamlit, pandas, caching, widgets, and Plotly.
After this chapter you will be able to
- Metrics and dashboard purpose. Explain how curated metrics give executives a high-level view of business performance and how a dashboard presents those metrics so leaders can explore data, spot important issues, and make informed decisions.
- Dashboard business need. Explain why Note n’ Nib Inc. needs a metrics dashboard: its sales reporting is outdated and paper-based, while the new CEO wants current daily sales information to support decisions.
- Dashboard concept. State that the app is a dashboard for executives to view various cuts of sales data and track key metrics for decision-making.
- Sales data structure. Describe the Note n’ Nib sales dataset, including its dimensions, measures, time span, and row-level uniqueness. Explain how one row represents sales activity for a particular date, product, customer demographic, and state.
- Dashboard feature requirements. State the dashboard’s four key metrics and the ways users must be able to examine them. Describe the required filtering and trend visualizations across time and the specified business dimensions.
- Dashboard information hierarchy. Describe how the dashboard mock makes the four key metrics the most prominent elements, using a large, immediately noticeable display.
- Filter-controlled data slice. Explain how the dashboard controls define the slice of data shown: filters appear at the top and a date range selector appears on the left, and both affect the metric values and displayed data.
- Trend and breakdown charts. Distinguish the two visualizations in the mock: a line chart shows how a selected metric changes over time, while a pie chart shows how total sales or gross margin breaks down by a selected dimension such as product category.
- Dashboard data-flow architecture. Describe the high-level dashboard flow: load raw CSV data into memory, optionally prepare it, apply global filters, then send filtered data to the dashboard displays for further transformation.
- Global filter application. Explain why the filter bar and date range selectors are global and should be applied before data is passed to the metric bar and charts.
- Display-specific data transformations. Describe how the metric bar, time-series line chart, and pie chart each require transformations of filtered data, including grouping, aggregation, or other reshaping; explain that chart options provide inputs to those transformations.
- External data loading workflow. Describe the basic data-loading workflow for a data application: obtain data from a source, load it into the app, keep it in memory, and display it in Streamlit. State that this dashboard will use a previously reviewed CSV file as its external source.
- CSV dataframe loading. Explain that a pandas dataframe is a two-dimensional table of rows and columns, and describe loading sales_data.csv into a dataframe with pd.read_csv after importing pandas as pd.
- Column selection and preview. Describe creating a smaller dataframe by selecting a list of column names with dataframe square-bracket notation, then using head() to display the first five rows.
- Module-based data loading. Describe how the dashboard separates CSV-reading logic into data_loader.py and uses dashboard.py as the Streamlit entry point. Explain that load_data returns the pandas dataframe that dashboard.py uses.
- Deployment-safe CSV paths. Explain why a relative filename such as sales_data.csv is resolved from Python's working directory rather than from data_loader.py's directory. Trace how Path(__file__).resolve().parent / "sales_data.csv" constructs an absolute, portable path to the CSV.
- Repeated CSV loading cost. Explain why loading the large CSV on every Streamlit rerun slows and wastes work in the dashboard. Relate user interactions such as changing a selection or leaving a text box to rerunning the script and therefore rereading the file.
- Caching expensive data loads. Explain why repeatedly reading data is costly under Streamlit’s execution model and how st.cache_data avoids repeating a slow function call with the same parameters.
- Cache decorator application. Describe how to apply st.cache_data to load_data as a Python decorator by placing @st.cache_data above the function, and state that data_loader.py must import Streamlit to use it.
- Cache expiration with TTL. Explain why a permanently cached CSV can become stale and how the ttl argument sets how long cached data remains valid before Streamlit reruns and re-caches the function.
- Dashboard data filtering. Explain why the dashboard filters its source data and define filtering as retaining relevant rows while excluding the others.
- Filtering interface components. Describe the two planned dashboard components for filtering: a filter panel for selecting field values and a date range selector for selecting a period of data.
- Filter panel behavior. Describe the filter panel as one multi-select dropdown per chosen dataframe field, where users may select multiple values and an empty selection means that field does not filter the data.
- Data-driven filter options. Explain how get_unique_values obtains dropdown options dynamically by selecting a dataframe column, calling .unique() to deduplicate its values, and converting the result to a Python list.
- Dictionary-based dataframe filtering. Trace how filter_panel collects each st.multiselect return value into a filters dictionary keyed by field name, then how apply_filters iterates over it and uses df[col].isin(values) with boolean indexing to retain matching rows only when values is nonempty.
- Date range panel. Describe how the date_range_panel function uses two st.date_input widgets to collect a start date and an end date, then returns the user-selected dates.
- Inclusive dataframe date filtering. Trace how the selected Python date values are converted for pandas and applied to the dataframe: prep_data creates a datetime[ns] Day column from Date, get_filtered_data_within_date_range combines existing filters with the date-range filter, and boolean indexing retains rows from start through end inclusively.
- Business metrics meaning. Explain what metrics are and how they reduce the complexity of a business or project to a few figures, using examples such as earnings, profit, revenue growth, customer-acquisition cost, or cost.
- Metric trend interpretation. Describe how changes in positive and negative metrics signal business performance: rising positive metrics such as profit and falling negative metrics such as cost suggest things are going well, while the opposite suggests something may need to change.
- Dashboard metric calculations. Explain how to calculate total sales, gross margin, margin percentage, and average transaction value for any filtered slice of the CSV data. State which columns are summed and that the percentage and average are calculated from the resulting totals.
- Configuration-driven metric design. Explain why the dashboard defines metrics in a configuration file rather than hardcoding each metric directly in the app. Describe how this general design makes the dashboard easier to adapt and maintain when metrics, ordering, or displayed selections change.
- Metric dataclass structure. Describe the Metric dataclass and the purpose of its title, type, and func members. Explain that func is a callable which receives a pandas dataframe and returns the metric's calculated value, while title and type control its display label and formatting.
- Metrics dictionary and display list. Describe how the metrics dictionary maps metric names to Metric objects and how display_metrics specifies which configured metrics appear in the metric bar and in what order. Explain the total-sales example as a lambda that sums the Sales column, and distinguish ratio metrics that use named functions to guard against a zero denominator.
- Metric type formatting logic. Explain how format_metric uses a numeric value and a metric type to select the appropriate display formatting. Describe that dollar and percent metrics receive specialized formatting, while unrecognized types are displayed unchanged.
- Abbreviated dollar displays. Describe how dollar-type metrics are formatted with humanize.metric and a manually added dollar sign. Explain that large raw values are rounded and abbreviated with suffixes such as k or m to reduce cognitive load, for example turning 25,125,367 into $25.1m.
- Metric bar rendering flow. Describe how the metric_bar function renders the configured metrics: it iterates over display_metrics, creates an st.metric element for each metric, and places each one in its assigned display column.
- Executive dashboard visualizations. Explain why graphs can communicate data more memorably and quickly than tables of numbers, particularly for busy executives making informed decisions.
- Dashboard chart purposes. Describe the two planned dashboard visualizations: a line chart for showing how tracked metrics change over time and a pie chart for showing their breakdown across a chosen dimension.
- Metric time-series aggregation. Explain how filtered dashboard rows are aggregated to one Day-and-Value record per date for a selected metric. Describe how grouping by Day, applying the metric’s function to each group, and resetting the index produces chart-ready data.
- Plotly line-chart construction. Describe how a Plotly Graph Objects Figure becomes a metric line chart: obtain the metric time series, create a go.Figure, add a go.Scatter trace using Day for x and Value for y with lines and markers, and set chart and axis titles.
- Pie chart metric suitability. Explain why the pie chart is used to show parts of a whole and why it offers only Total sales and Gross margin, rather than Margin % or ATV.
- Dimension-based metric grouping. Describe how get_metric_grouped_by_dimension prepares pie-chart data by grouping the filtered data by a chosen dimension and aggregating the selected metric for each dimension value.
- Plotly pie chart integration. Describe how the dashboard builds and displays the pie chart with Plotly go.Pie using category labels, aggregated values, and a hole setting, while letting users select a breakdown dimension and showing a tab per eligible metric.
What it builds on
- What is Streamlit? (chapter 1) · The introductory definition of Streamlit as a Python framework for building web apps.
- Stating our concept: A unit converter (chapter 3) · The practice of stating an app concept before defining requirements and implementation.
- Visualizing the user experience (chapter 3) · The idea of creating a mock to visualize the user experience before implementation.
- Brainstorming the implementation (chapter 3) · The practice of mapping an app’s logic before writing code.
- Building your first app (chapter 2) · Basic experience building and running a Streamlit app.
- Virtual environments (chapter 2) · Using a Python environment and installing project dependencies.
- Going through the code (chapter 2) · Basic Python variables, imports, and running app code.
- App reruns (chapter 4) · Streamlit's model of rerunning the entire script when the interface changes.
Section by section
Introduction
This chapter introduces why executive metrics dashboards matter and previews building an interactive CEO KPI dashboard with Streamlit, pandas, caching, widgets, and Plotly.
- Metrics and dashboard purpose: Explain how curated metrics give executives a high-level view of business performance and how a dashboard presents those metrics so leaders can explore data, spot important issues, and make informed decisions.
Why it matters: A dashboard is valuable when it turns raw numbers into a clear story that helps decision-makers focus on what matters. - Dashboard development roadmap: Describe the chapter's planned dashboard work: loading and wrangling data with pandas, caching function results for performance, adding interactive filters and widgets, and creating charts and visualizations with Plotly in Streamlit.
Why it matters: These pieces form the practical path from source data to an interactive dashboard a CEO can use. - Chapter code resources: State that the book repository's chapter_06 folder contains this chapter's code and a requirements.txt file with exact library versions, which can be installed with pip install -r requirements.txt.
Why it matters: Using the provided dependency file helps reproduce the chapter environment with the intended library versions.
Key terms: metrics, dashboard, key performance indicators, KPIs, pandas, caching, filters, widgets, Plotly, Streamlit
6.1 A metrics dashboard
Introduces the business need for a timely sales metrics dashboard and frames Streamlit as the tool for building it without burdening Engineering.
- Dashboard business need: Explain why Note n’ Nib Inc. needs a metrics dashboard: its sales reporting is outdated and paper-based, while the new CEO wants current daily sales information to support decisions.
Why it matters: A useful dashboard starts by solving a concrete decision-making problem rather than merely displaying charts. - Streamlit implementation opportunity: Describe why the narrator proposes Streamlit for the dashboard: Engineering is occupied with a major website overhaul, and the narrator wants to use the Python framework to build the requested metrics page instead of adding work to Engineering.
Why it matters: Streamlit can enable a team to deliver an internal business tool when a conventional engineering team has limited capacity.
Key terms: metrics dashboard, daily sales data, Streamlit, Python framework, Engineering
6.1.1 Stating the concept
Defines the CEO dashboard as a decision-support view of sales data and key metrics for executives.
- Dashboard concept: State that the app is a dashboard for executives to view various cuts of sales data and track key metrics for decision-making.
Why it matters: A clear concept keeps the dashboard focused on the information executives need to make decisions.
Key terms: dashboard, sales data, key metrics, executives
6.1.2 Defining the requirements
This section turns the CEO dashboard concept into a concrete data description, feature requirements, and deliberately limited first-release scope.
- Sales data structure: Describe the Note n’ Nib sales dataset, including its dimensions, measures, time span, and row-level uniqueness. Explain how one row represents sales activity for a particular date, product, customer demographic, and state.
Why it matters: Understanding what each row and field represents is necessary before filtering, aggregating, or displaying dashboard results. - Dashboard feature requirements: State the dashboard’s four key metrics and the ways users must be able to examine them. Describe the required filtering and trend visualizations across time and the specified business dimensions.
Why it matters: These requirements define the initial dashboard experience rather than leaving “various cuts” and “key metrics” ambiguous. - Initial release boundaries: Distinguish the dashboard’s initial observational scope from features explicitly excluded at launch: row-level drilldowns, forecasting, and explanations for metric changes. Explain that these limits keep the first version focused and quick to deliver.
Why it matters: Clear exclusions prevent extra requests from expanding the first dashboard beyond its intended observational purpose. - CSV source tradeoff: Explain why the chapter uses a CSV file even though it is static and inefficient as a typical production dashboard source. State that this choice keeps attention on working with data inside the app, while a later chapter replaces the source with a data warehouse.
Why it matters: This clarifies that the CSV is a teaching simplification rather than a recommendation for production dashboards.
Key terms: sales_data.csv, CSV, sales, gross margin, transactions, primary key, total sales, margin percentage, average transaction value, filters
6.1.3 Visualizing the user experience
This section turns the dashboard requirements into a UI mock that prioritizes key metrics, filtering controls, and charts for trends and breakdowns.
- Dashboard information hierarchy: Describe how the dashboard mock makes the four key metrics the most prominent elements, using a large, immediately noticeable display.
Why it matters: A CEO-facing dashboard must make its most important information easy to spot at a glance. - Filter-controlled data slice: Explain how the dashboard controls define the slice of data shown: filters appear at the top and a date range selector appears on the left, and both affect the metric values and displayed data.
Why it matters: Filters let a leader view the same dashboard measures for the particular dimensions and time period they care about. - Trend and breakdown charts: Distinguish the two visualizations in the mock: a line chart shows how a selected metric changes over time, while a pie chart shows how total sales or gross margin breaks down by a selected dimension such as product category.
Why it matters: Choosing a chart that matches the question helps users quickly understand both performance over time and composition of a total.
Key terms: key metrics, UI mock, filters, date range selector, slice of the data, dimensions, cuts, time series chart, line chart, pie chart
6.1.4 Brainstorming the implementation
This section outlines the dashboard’s data flow, from loading and preparing CSV data through global filtering and visualization-specific transformations.
- Dashboard data-flow architecture: Describe the high-level dashboard flow: load raw CSV data into memory, optionally prepare it, apply global filters, then send filtered data to the dashboard displays for further transformation.
Why it matters: This flow keeps shared data handling separate from the calculations and charts that present it. - Global filter application: Explain why the filter bar and date range selectors are global and should be applied before data is passed to the metric bar and charts.
Why it matters: Applying shared filters early ensures every dashboard widget reflects the same selected subset of data. - Display-specific data transformations: Describe how the metric bar, time-series line chart, and pie chart each require transformations of filtered data, including grouping, aggregation, or other reshaping; explain that chart options provide inputs to those transformations.
Why it matters: The same filtered dataset must be shaped differently to produce meaningful headline metrics and visualizations.
Key terms: raw data, CSV file, data preparation, global filters, filtered data, transformations, filter bar, date range selectors, global, widgets
6.2 Loading the data
This section introduces loading external CSV data into a Streamlit app, using pandas to hold and display it, and caching large data loads for performance.
- External data loading workflow: Describe the basic data-loading workflow for a data application: obtain data from a source, load it into the app, keep it in memory, and display it in Streamlit. State that this dashboard will use a previously reviewed CSV file as its external source.
Why it matters: A dashboard cannot filter, calculate, or visualize information until its source data is available in the app. - Pandas data manipulation role: Explain that pandas is the Python library introduced here for data manipulation while working with the dashboard's loaded data.
Why it matters: Pandas provides the data-manipulation capability used as the dashboard begins working with its data. - Caching for large data: Explain that caching can improve app performance when the data being loaded is very large.
Why it matters: Caching addresses the performance cost of loading large amounts of data.
Key terms: external source, CSV file, loading data, in memory, Streamlit, pandas, data manipulation, caching, performance, large data
6.2.1 The pandas library
This section introduces pandas through installing it, loading the sales CSV into a dataframe, inspecting its structure and types, and previewing selected columns.
- Pandas installation and verification: Describe how to install pandas with pip and verify that the installation succeeded using pip show pandas.
Why it matters: You need pandas available in your Python environment before the dashboard can load and work with tabular sales data. - CSV dataframe loading: Explain that a pandas dataframe is a two-dimensional table of rows and columns, and describe loading sales_data.csv into a dataframe with pd.read_csv after importing pandas as pd.
Why it matters: The dataframe is the central in-memory structure the dashboard uses to prepare, filter, calculate, and display sales data. - Dataframe structure inspection: Describe using Python's type function and a dataframe's info() method to inspect the loaded data, including its row and column counts and the types of its columns.
Why it matters: Inspecting a dataframe confirms that the file loaded as expected and reveals the structure you must work with. - Pandas dtype backends: Distinguish pandas dtypes such as object and float64 from regular Python types, and explain that pandas derives these efficient computation types from NumPy; describe the optional Apache Arrow dtype backend when reading a CSV.
Why it matters: Recognizing dataframe dtypes helps you interpret inspection output and choose an optional backend for large datasets. - Column selection and preview: Describe creating a smaller dataframe by selecting a list of column names with dataframe square-bracket notation, then using head() to display the first five rows.
Why it matters: Selecting relevant columns and previewing their values are practical first steps before building dashboard filters, metrics, and charts.
Key terms: pip, pip show pandas, pandas, dataframe, import pandas as pd, pd.read_csv, sales_data.csv, type(), info(), object
6.2.2 Reading and displaying a dataframe
This section separates CSV loading into a module, builds a deployment-safe path to the file, and displays a dataframe preview in Streamlit while motivating caching.
- Module-based data loading: Describe how the dashboard separates CSV-reading logic into data_loader.py and uses dashboard.py as the Streamlit entry point. Explain that load_data returns the pandas dataframe that dashboard.py uses.
Why it matters: Separating the loader from the app entry point keeps a larger dashboard easier to organize and extend. - Deployment-safe CSV paths: Explain why a relative filename such as sales_data.csv is resolved from Python's working directory rather than from data_loader.py's directory. Trace how Path(__file__).resolve().parent / "sales_data.csv" constructs an absolute, portable path to the CSV.
Why it matters: Building the path from the executing file prevents the app from failing when it runs from a different working directory or computer. - Dataframe preview with st.write: Describe how st.write(data.head(5)) displays the first five rows of the loaded pandas dataframe to verify that loading worked. State that st.write can render many kinds of Python objects in an appropriate format, including dataframes.
Why it matters: A small dataframe preview provides a quick visual check that the app loaded the expected data. - Repeated CSV loading cost: Explain why loading the large CSV on every Streamlit rerun slows and wastes work in the dashboard. Relate user interactions such as changing a selection or leaving a text box to rerunning the script and therefore rereading the file.
Why it matters: Recognizing repeated work is the reason to cache loaded data in the next section.
Key terms: data_loader.py, dashboard.py, load_data, entry point, pandas dataframe, working directory, __file__, Path, pathlib, .resolve()
6.2.3 Caching data
This section uses st.cache_data to cache a dashboard’s loaded dataframe across reruns, refreshes, and users while controlling freshness and loading feedback.
- Caching expensive data loads: Explain why repeatedly reading data is costly under Streamlit’s execution model and how st.cache_data avoids repeating a slow function call with the same parameters.
Why it matters: Caching keeps a data app responsive instead of redoing the same expensive work on every interaction. - Cache decorator application: Describe how to apply st.cache_data to load_data as a Python decorator by placing @st.cache_data above the function, and state that data_loader.py must import Streamlit to use it.
Why it matters: Using the decorator is the concrete change that turns the existing data loader into a cached loader. - Cache expiration with TTL: Explain why a permanently cached CSV can become stale and how the ttl argument sets how long cached data remains valid before Streamlit reruns and re-caches the function.
Why it matters: A time-to-live setting balances fast dashboard loading with the CEO’s need for up-to-date sales data. - Shared cache and loading feedback: Describe that cached values are shared across app users rather than limited to one session, and explain how show_spinner can replace the internal function-name spinner text with a user-friendly loading message.
Why it matters: Shared cached data makes common dashboard data efficient for everyone, while a clear loading message gives users understandable feedback when loading occurs.
Key terms: st.cache_data, cache, load_data, dataframe, rerun, @st.cache_data, decorator, data_loader.py, import streamlit as st, ttl
6.3 Prepping and filtering the data
This section introduces filtering the dashboard data into relevant slices using a filter panel and date range selector, supported by pandas data wrangling.
- Dashboard data filtering: Explain why the dashboard filters its source data and define filtering as retaining relevant rows while excluding the others.
Why it matters: Filtering lets dashboard users focus on the subset of data that answers their current question rather than all available history. - Filtering interface components: Describe the two planned dashboard components for filtering: a filter panel for selecting field values and a date range selector for selecting a period of data.
Why it matters: These controls give users direct ways to choose the data slice they want to inspect. - Pandas filtering work: State that the section will pair the visual filtering components with pandas data wrangling that makes their filtering functionality work.
Why it matters: The visible controls need data manipulation behind the scenes to produce the selected subset.
Key terms: filtering, rows of data, slices of the data, filter panel, date range selector, field values, pandas, data wrangling
6.3.1 Creating a filter panel
This section builds a polished multi-select filter panel that derives options from dashboard data and applies users’ selections to a dataframe.
- Filter panel behavior: Describe the filter panel as one multi-select dropdown per chosen dataframe field, where users may select multiple values and an empty selection means that field does not filter the data.
Why it matters: This defines how dashboard users narrow the data without accidentally excluding everything. - Data-driven filter options: Explain how get_unique_values obtains dropdown options dynamically by selecting a dataframe column, calling .unique() to deduplicate its values, and converting the result to a Python list.
Why it matters: Generating options from the data keeps filters current when products, categories, age groups, or other values change. - Polished filter panel layout: Describe how filter_panel renders one dropdown per filter dimension in side-by-side st.columns inside an st.expander, and how a wide page layout gives a dense dashboard more horizontal room.
Why it matters: A compact, collapsible, wide layout makes a six-filter dashboard easier to use and lets users focus on the displayed data. - Prepared data labels and caching: Explain that prep_data applies shared data preparation, currently cleaning column names by replacing underscores with spaces and capitalizing them, and that st.cache_data belongs on prep_data so Streamlit caches the prepared result.
Why it matters: Preparing data once gives the dashboard friendly labels while caching the form of data the app actually uses. - Dictionary-based dataframe filtering: Trace how filter_panel collects each st.multiselect return value into a filters dictionary keyed by field name, then how apply_filters iterates over it and uses df[col].isin(values) with boolean indexing to retain matching rows only when values is nonempty.
Why it matters: This is the connection between the filter UI and the actual subset of data used by the dashboard.
Key terms: filter panel, st.multiselect, filter dimensions, get_unique_values, pandas dataframe, column selection, pandas series, .unique(), filter_panel, st.columns
6.3.2 Creating a date range selector
This section adds sidebar start/end date inputs and uses their selections to filter the dashboard dataframe efficiently by an inclusive date range.
- Date range panel: Describe how the date_range_panel function uses two st.date_input widgets to collect a start date and an end date, then returns the user-selected dates.
Why it matters: The dashboard needs a simple interface for narrowing every result to the period the user cares about. - Default date boundaries: Explain the default date-range values: LATEST_DATE is a date available in the static CSV, and THIRTY_DAYS_AGO is calculated by subtracting a 30-day timedelta from it; for live data, LATEST_DATE could instead be date.today().
Why it matters: Defaults must match the available dataset, or the dashboard can initially show an irrelevant or empty period. - Inclusive dataframe date filtering: Trace how the selected Python date values are converted for pandas and applied to the dataframe: prep_data creates a datetime[ns] Day column from Date, get_filtered_data_within_date_range combines existing filters with the date-range filter, and boolean indexing retains rows from start through end inclusively.
Why it matters: Correct type conversion and inclusive boolean conditions make the displayed dashboard data match the dates the user selected. - Dashboard filter integration: Describe how dashboard.py places the date range panel in the sidebar and assigns main_df from get_filtered_data_within_date_range, which now wraps the prior apply_filters call.
Why it matters: Wiring the panel into the dashboard ensures that downstream metrics and charts use the user-filtered data.
Key terms: st.date_input, date_range_panel, start, end, LATEST_DATE, THIRTY_DAYS_AGO, timedelta, date.today(), date, prep_data
6.4 Calculating and displaying metrics
This section introduces business metrics as concise indicators of performance and previews calculating, configuring, and prominently displaying the metrics important to Note n’ Nib’s CEO.
- Business metrics meaning: Explain what metrics are and how they reduce the complexity of a business or project to a few figures, using examples such as earnings, profit, revenue growth, customer-acquisition cost, or cost.
Why it matters: Metrics give decision-makers a compact way to assess whether a business is doing well. - Metric trend interpretation: Describe how changes in positive and negative metrics signal business performance: rising positive metrics such as profit and falling negative metrics such as cost suggest things are going well, while the opposite suggests something may need to change.
Why it matters: Interpreting direction of change turns dashboard numbers into signals for action. - Dashboard metric workflow: State the planned workflow for Note n’ Nib’s CEO metrics: understand what each metric means and how to calculate it, define metrics in a scalable way, and display them prominently in the dashboard.
Why it matters: A scalable definition-and-display approach makes it easier to add and present metrics consistently.
Key terms: metrics, earnings, profit, revenue growth, customer acquisition cost, positive metric, negative metric, cost, Note n’ Nib, metrics configuration
6.4.1 Calculating the metrics
This section defines the dashboard’s four business metrics and shows how to calculate each from an aggregated slice of the sales data.
- Dashboard metric calculations: Explain how to calculate total sales, gross margin, margin percentage, and average transaction value for any filtered slice of the CSV data. State which columns are summed and that the percentage and average are calculated from the resulting totals.
Why it matters: These calculations turn filtered transaction data into the headline numbers a CEO can use to assess business performance. - Sales data grain and meanings: Describe what one source-data row represents and distinguish sales, gross margin, and transactions. Explain that gross margin is profit: sales minus the cost of acquiring the items sold.
Why it matters: Understanding what each row and numeric field represent prevents using the wrong denominator or interpreting the metrics incorrectly.
Key terms: total sales, gross margin, margin percentage, average transaction value, sales, transactions, source CSV, transaction, date
6.4.2 Setting up the metrics configuration
This section defines a flexible, configuration-driven way to describe dashboard metrics, their calculations, formatting, and display selection.
- Configuration-driven metric design: Explain why the dashboard defines metrics in a configuration file rather than hardcoding each metric directly in the app. Describe how this general design makes the dashboard easier to adapt and maintain when metrics, ordering, or displayed selections change.
Why it matters: A configuration-driven design lets you change dashboard metrics without scattering metric-specific logic throughout the app. - Metric dataclass structure: Describe the Metric dataclass and the purpose of its title, type, and func members. Explain that func is a callable which receives a pandas dataframe and returns the metric's calculated value, while title and type control its display label and formatting.
Why it matters: Separating a metric's calculation from its presentation lets one consistent dashboard component handle many different metrics. - Metrics dictionary and display list: Describe how the metrics dictionary maps metric names to Metric objects and how display_metrics specifies which configured metrics appear in the metric bar and in what order. Explain the total-sales example as a lambda that sums the Sales column, and distinguish ratio metrics that use named functions to guard against a zero denominator.
Why it matters: The dictionary and display list provide a controlled path from a named metric definition to a safely calculated, intentionally ordered dashboard display.
Key terms: configuration file, metric_config.py, general design, hardcoding, Metric, dataclass, title, type, func, callable
6.4.3 Formatting the metrics
This section defines how dashboard metric values are converted into concise display strings based on their configured metric types.
- Metric type formatting logic: Explain how format_metric uses a numeric value and a metric type to select the appropriate display formatting. Describe that dollar and percent metrics receive specialized formatting, while unrecognized types are displayed unchanged.
Why it matters: A metric’s type lets the dashboard present the same underlying numeric data in a form a CEO can quickly interpret. - Abbreviated dollar displays: Describe how dollar-type metrics are formatted with humanize.metric and a manually added dollar sign. Explain that large raw values are rounded and abbreviated with suffixes such as k or m to reduce cognitive load, for example turning 25,125,367 into $25.1m.
Why it matters: Abbreviated currency values make large business figures easier to scan without overwhelming the dashboard user with unnecessary precision. - Percentage conversion formatting: Explain that percent metrics are stored as fractions for formatting purposes, so the formatter multiplies the value by 100, rounds it to one decimal place, and appends a percent sign.
Why it matters: Converting fractional values to readable percentages prevents a value such as 0.25 from being displayed misleadingly as 0.25%.
Key terms: Metric class, metric type, format_metric, dollars type, percent type, humanize, humanize.metric, cognitive load, fraction, percentage
6.4.4 Displaying the metrics
This section implements the dashboard’s bordered metric bar by rendering configured metrics in Streamlit columns and using a nested-column layout to center each metric.
- Metric bar rendering flow: Describe how the metric_bar function renders the configured metrics: it iterates over display_metrics, creates an st.metric element for each metric, and places each one in its assigned display column.
Why it matters: This turns the dashboard’s metric definitions and calculations into the executive-facing metric bar. - Metric value extraction: Explain that get_metric obtains a metric’s value from a dataframe by calling the func member already stored on its Metric object.
Why it matters: Keeping the calculation function on each Metric object lets the display code retrieve different metrics through one simple interface. - Centered metric column layout: Explain the nested-column layout hack used to center each st.metric: each main metric column is split into three sub-columns, with equal-width blank outer columns and the metric placed in the middle column.
Why it matters: The layout achieves horizontal centering even though Streamlit does not provide a good direct way to center an item in a column without HTML. - Bordered metric bar container: State that the metric bar is placed inside st.container to show it within a bordered box, while recognizing that containers can also support displaying elements in a different order from their code later in the book.
Why it matters: The container visually groups the dashboard’s key metrics and introduces a Streamlit layout element with broader uses.
Key terms: metric_bar, display_metrics, st.metric, display column, get_metric, Metric, func, dataframe, metric_cols, st.columns
6.5 Constructing visualizations
This section introduces why executive dashboards need visualizations and previews building time-series and breakdown charts with pandas, Plotly, and Streamlit.
- Executive dashboard visualizations: Explain why graphs can communicate data more memorably and quickly than tables of numbers, particularly for busy executives making informed decisions.
Why it matters: Visual summaries help decision-makers grasp the business quickly instead of interpreting a table cell by cell. - Dashboard chart purposes: Describe the two planned dashboard visualizations: a line chart for showing how tracked metrics change over time and a pie chart for showing their breakdown across a chosen dimension.
Why it matters: Each chart answers a different business question: change over time versus composition across a dimension. - Visualization construction workflow: Trace the planned visualization workflow: use pandas to wrangle data into a chart-ready form, create the chart images with Plotly, and display them with Streamlit.
Why it matters: Separating data preparation, chart creation, and app display makes it clear how the dashboard turns data into visible charts.
Key terms: visualizations, graphs, tables of numbers, executives, line chart, pie chart, tracked metrics, chosen dimension, pandas, wrangle
6.5.1 Creating a time series chart
This section transforms filtered dashboard data into metric time series, builds interactive Plotly line charts, and presents one chart per metric in Streamlit tabs.
- Metric time-series aggregation: Explain how filtered dashboard rows are aggregated to one Day-and-Value record per date for a selected metric. Describe how grouping by Day, applying the metric’s function to each group, and resetting the index produces chart-ready data.
Why it matters: A line chart is only meaningful when the detailed filtered records have been correctly rolled up to the time level being displayed. - Plotly line-chart construction: Describe how a Plotly Graph Objects Figure becomes a metric line chart: obtain the metric time series, create a go.Figure, add a go.Scatter trace using Day for x and Value for y with lines and markers, and set chart and axis titles.
Why it matters: This is the chart-building pattern that turns the aggregated data into an interactive visualization for dashboard users. - Tabbed chart presentation: Explain how the dashboard displays one metric chart per Streamlit tab inside a bordered container. Describe that st.tabs receives the display metric names, each corresponding tab renders its Plotly Figure with st.plotly_chart and use_container_width=True, and tab switches do not rerun the app.
Why it matters: Tabs provide fast metric switching while preserving a compact dashboard layout, but they require all charts to be created on the initial load.
Key terms: time series, groupby, apply, lambda function, include_groups=False, reset_index, Plotly Graph Objects, go, Figure, go.Figure
6.5.2 Creating a pie chart
This section adds a donut-style pie chart that breaks additive dashboard metrics down by a selected dimension and places it beside the time-series chart.
- Pie chart metric suitability: Explain why the pie chart is used to show parts of a whole and why it offers only Total sales and Gross margin, rather than Margin % or ATV.
Why it matters: Choosing an additive metric prevents a pie chart from presenting misleading percentage shares. - Dimension-based metric grouping: Describe how get_metric_grouped_by_dimension prepares pie-chart data by grouping the filtered data by a chosen dimension and aggregating the selected metric for each dimension value.
Why it matters: The chart needs one metric value per category before Plotly can turn those values into percentage slices. - Plotly pie chart integration: Describe how the dashboard builds and displays the pie chart with Plotly go.Pie using category labels, aggregated values, and a hole setting, while letting users select a breakdown dimension and showing a tab per eligible metric.
Why it matters: This connects the prepared data, user controls, and Plotly rendering into an interactive dashboard visualization.
Key terms: Total sales, Gross margin, Margin %, ATV, pie-chart-applicable metrics, get_metric_grouped_by_dimension, get_metric_time_series, dimension, group by, Day
6.6 Summary
This summary recaps the data loading, filtering, metric display, and visualization techniques used to build a Streamlit metrics dashboard.
Where this is used later
- (chapter intro) (chapter 7) · The original concept and requirements for the Note n’ Nib metrics dashboard.
- A drilldown view (chapter 7) · The original dashboard was conceived as a metrics dashboard for presenting business data clearly.
- Date range comparisons (chapter 7) · Date range comparisons extend the initial dashboard beyond its original basic observation features.
- Sourcing data from a data warehouse (chapter 7) · Moving from the static CSV to BigQuery addresses the later evolution of the data source.
- Showing the comparison in the metric bar (chapter 7) · This section extends the metric bar to show date-range comparisons.
- Interdependent filters (chapter 7) · This section develops the dashboard filters into interdependent filters.
- Granularity in the time series chart (chapter 7) · This section adds different time granularities to the time series chart.
- Updating the dashboard to load data from BigQuery (chapter 7) · Updating the dashboard to load warehouse data may require attention to data-loading performance.
Concepts explained in this chapter
- PlotlyPlotly is a visualization library for creating interactive charts and graphs.
- st.plotly_chartst.plotly_chart is a Streamlit API function that renders a Plotly figure in an application.
- boolean indexingBoolean indexing is a data-selection technique that filters elements or rows according to Boolean conditions.
- average transaction valueAverage transaction value is the mean sales revenue associated with each transaction over a specified scope or period.
- multiselectA multi-select option is a user-interface control that lets a user choose multiple values from a set of options.
- st.set_page_configst.set_page_config is a Streamlit API function that sets page-level configuration such as layout and page metadata.
- filter panelA filter panel is a user-interface area containing controls that let users restrict displayed data by field values.
- SeriesA pandas Series is a one-dimensional labeled array-like data structure that stores values associated with an index.
- st.expanderst.expander is a Streamlit layout element that displays content inside a panel users can expand or collapse.
- vectorizationA text embedding model is a machine-learning model that converts text into numerical vectors representing its semantic content.
- data groupingPandas groupby is a dataframe operation that partitions rows into groups and supports aggregation across those groups.
- sequenceA time series is an ordered sequence of observations associated with time points, such as dates and corresponding values.
- pie chartA pie chart is a circular visualization that represents a whole as slices whose sizes correspond to component values or percentages.
- data frameA dataframe is a two-dimensional tabular data structure organized into rows and columns, with each column holding values of a data type.
- read_csvread_csv is a pandas function that reads delimited text data, commonly CSV files, into a dataframe.
- Plotly figureA Plotly figure is an object containing the traces, layout, and configuration that define a Plotly visualization.
- applyThe pandas apply method applies a function across dataframe rows, columns, groups, or Series values.
- grouped dataframeA grouped dataframe is a pandas data structure that partitions dataframe rows into groups for separate aggregation or transformation.
- st.tabsst.tabs is a Streamlit API function that creates selectable tab containers for organizing alternative content panels.
- salesSales are the monetary amounts collected from completed transactions.
- dimensionA dimension is a categorical or descriptive attribute by which data can be grouped, filtered, or analyzed.
- pandaspandas is a Python library for data manipulation and analysis, especially with labeled and tabular data.
- cachingCaching is the storage of computed results or loaded data so they can be reused without repeating the underlying work.
- date selectorA date range selector is a user-interface control for choosing a start date and end date that define a period of interest.
- st.cache_datast.cache_data is a Streamlit decorator or caching mechanism that stores function results and reuses them across reruns when inputs remain unchanged.
- dashboardA dashboard is an interface that presents selected metrics or other information for monitoring and decision-making.
- performanceA metric is a quantified measure used to describe or evaluate a phenomenon, process, or outcome.
- go.Piego.Pie is the Plotly Graph Objects trace class for representing pie-chart sectors from labels and values.
- decoratorA decorator is a Python construct that modifies or extends a function or class by wrapping it with additional behavior.
- gross marginGross margin is a profitability metric representing sales revenue remaining after subtracting the cost of goods sold.
- line plotA line chart is a visualization that represents ordered data points connected by line segments.
- pathlibpathlib is Python's standard library module for object-oriented filesystem path manipulation.
- st.writest.write is a Streamlit output function that renders supplied content in an application.
- visualizationData visualization is the graphical representation of data to support exploration, interpretation, and communication.
- metric barA metric bar is a dashboard interface area that presents multiple metrics in a horizontal layout.
- primary keyA primary key is a column or set of columns whose combined values uniquely identify each row in a data table.
- st.containerst.container is a Streamlit layout function that creates a container whose contents can be populated and rendered separately from the surrounding code order.
- lambdaA lambda function is an anonymous Python function defined as a single expression, typically for short computations.
- StreamlitStreamlit is an open-source Python framework for building interactive web applications, especially data and machine-learning applications.
- database transactionA database transaction is an atomic unit of database work whose modifications remain provisional until committed or are discarded by rollback.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
