Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Building Interactive Charts for Exploration, Communication, and Dashboardsยถ

Notebook Guideยถ

The original Plotly content remains intact. This added section clarifies what learners should extract from it.

Focus areasยถ

  • how interactivity changes analysis workflows

  • when hovering, zooming, and filtering add value

  • what makes an interactive chart stakeholder-friendly rather than distracting

  • how Plotly supports dashboards and exploratory investigation

px.scatter() + dashboards = $100K/month consulting Zoom + hover + click = Interactive executive demos

Tableau replacement = 100% Plotly in FAANG


๐ŸŽฏ Interactive = Stakeholder Engagement x10ยถ

FeatureStaticPlotly InteractiveBusiness Win
ZoomโŒ Fixedโœ… Drag to zoomDeep dive
HoverโŒ Manualโœ… Tooltip dataInstant insights
ClickโŒ Staticโœ… Filter dataDynamic analysis
ExportโŒ Screenshotโœ… PNG/PDF/CSVProfessional
DashboardโŒ PowerPointโœ… Live demo$1M deals closed

๐Ÿš€ Step 1: Interactive Scatter = ROI Explorer (Run this!)ยถ

## !pip install plotly pandas  # Run once!

import plotly.express as px
import pandas as pd
import numpy as np

## REAL BUSINESS DATA
np.random.seed(42)
df = pd.DataFrame({
    'Marketing_Spend': np.random.normal(40000, 15000, 100),
    'Sales': np.random.normal(60000, 20000, 100),
    'Product': np.random.choice(['Laptop', 'Phone', 'Tablet'], 100),
    'Region': np.random.choice(['North', 'South', 'East', 'West'], 100)
})
df['ROI'] = (df['Sales'] - df['Marketing_Spend']) / df['Marketing_Spend'] * 100

## ๐Ÿ–ฑ๏ธ INTERACTIVE SCATTER - CLICK + ZOOM + HOVER!
fig = px.scatter(df, x='Marketing_Spend', y='Sales',
                 size='ROI', color='Product',
                 hover_name='Product',
                 hover_data=['ROI', 'Region'],
                 title='๐Ÿ“ˆ Interactive Marketing ROI Explorer',
                 labels={'Marketing_Spend': 'Marketing Spend ($)',
                        'Sales': 'Sales Generated ($)',
                        'ROI': 'ROI (%)'})

fig.update_layout(
    width=900, height=600,
    title_font_size=20, title_x=0.5,
    showlegend=True
)
fig.show()

## BUSINESS INSIGHTS
print(f"๐Ÿ” Top ROI: {df['ROI'].max():.1f}%")
print(f"๐Ÿ“Š Best Product: {df.groupby('Product')['ROI'].mean().idxmax()}")

๐Ÿ”ฅ Step 2: Interactive Bar = Product Drilldownยถ

## INTERACTIVE BAR CHART
product_sales = df.groupby(['Product', 'Region']).agg({
    'Sales': 'mean',
    'Marketing_Spend': 'mean'
}).round(0).reset_index()

fig = px.bar(product_sales, x='Product', y='Sales',
             color='Region',
             title='๐Ÿ† Interactive Product Sales by Region',
             labels={'Sales': 'Average Sales ($)'},
             text='Sales')

fig.update_traces(texttemplate='%{text:$,.0f}', textposition='outside')
fig.update_layout(
    width=800, height=500,
    title_font_size=20, title_x=0.5
)
fig.show()

โšก Step 3: Interactive Line = Sales Trend Explorerยถ

## TIME SERIES WITH ZOOM
dates = pd.date_range('2024-01-01', periods=100, freq='D')
sales_trend = 50000 + np.cumsum(np.random.normal(500, 2000, 100))

df_trend = pd.DataFrame({
    'Date': dates,
    'Sales': sales_trend,
    'Product': np.random.choice(['Laptop', 'Phone', 'Tablet'], 100)
})

fig = px.line(df_trend, x='Date', y='Sales',
              color='Product',
              title='๐Ÿ“Š Interactive Sales Trend (Zoom + Pan)',
              labels={'Sales': 'Daily Sales ($)'})

fig.update_layout(
    width=1000, height=500,
    title_font_size=20, title_x=0.5,
    xaxis_title="Date",
    yaxis_title="Daily Sales ($)"
)
fig.show()

print(f"๐Ÿ“ˆ 30-day growth: {((sales_trend[-30:].mean() - sales_trend[:30].mean()) / sales_trend[:30].mean() * 100):+.1f}%")

๐Ÿง  Step 4: FULL INTERACTIVE DASHBOARDยถ

from plotly.subplots import make_subplots
import plotly.graph_objects as go

## EXECUTIVE DASHBOARD TEMPLATE
fig = make_subplots(
    rows=2, cols=2,
    subplot_titles=('๐Ÿ’ฐ Sales Trend', '๐Ÿ† Product Mix', '๐Ÿ“ˆ ROI Scatter', '๐Ÿ”ฅ Regional Heatmap'),
    specs=[[{"type": "scatter"}, {"type": "pie"}],
           [{"type": "scatter"}, {"type": "heatmap"}]]
)

## 1. SALES TREND
fig.add_trace(go.Scatter(x=df_trend['Date'][-30:], y=df_trend['Sales'][-30:],
                        mode='lines+markers', name='Sales'), row=1, col=1)

## 2. PRODUCT PIE
product_agg = df.groupby('Product')['Sales'].sum()
fig.add_trace(go.Pie(labels=product_agg.index, values=product_agg.values,
                    name='Product Mix'), row=1, col=2)

## 3. ROI SCATTER
fig.add_trace(go.Scatter(x=df['Marketing_Spend'], y=df['Sales'],
                        mode='markers', marker=dict(size=8, color=df['ROI'], colorscale='Viridis'),
                        name='ROI'), row=2, col=1)

## 4. REGIONAL HEATMAP
pivot = df.pivot_table(values='Sales', index='Product', columns='Region', aggfunc='mean')
fig.add_trace(go.Heatmap(z=pivot.values, x=pivot.columns, y=pivot.index,
                        colorscale='YlOrRd'), row=2, col=2)

fig.update_layout(
    height=800, width=1200,
    title_text="๐Ÿš€ EXECUTIVE INTERACTIVE DASHBOARD",
    title_font_size=24, title_x=0.5
)
fig.show()

๐Ÿ“Š Step 5: Click + Filter Interactive Tableยถ

import plotly.graph_objects as go
from plotly.offline import iplot

## INTERACTIVE DATA TABLE
fig = go.Figure(data=[go.Table(
    columnwidth=[100, 100, 100, 120],
    header=dict(
        values=['Product', 'Region', 'Sales', 'ROI %'],
        line_color='darkslategray',
        fill_color='royalblue',
        font=dict(color='white', size=14),
        height=40
    ),
    cells=dict(
        values=[df['Product'], df['Region'],
                [f'${s:,.0f}' for s in df['Sales']],
                [f'{r:.1f}%' for r in df['ROI']]],
        line_color='darkslategray',
        fill_color=['paleturquoise', 'lightcyan'],
        font=dict(color='darkslategray', size=12),
        height=30
    ))
])

fig.update_layout(
    title="๐Ÿ“‹ Interactive Sales Data Table",
    title_font_size=20, title_x=0.5,
    width=800, height=600
)
fig.show()

๐Ÿ“‹ Plotly Cheat Sheet (Consulting Gold)ยถ

ChartCodeInteractive MagicBusiness Demo
Scatterpx.scatter(x,y,size,color)Zoom + hoverROI analysis
Barpx.bar(x,y,color)Click to filterProduct ranking
Linepx.line(x,y,color)Pan + zoomSales trends
Piepx.pie(names,values)Explode slicesMarket share
Heatmappx.imshow()Cell hoverPerformance matrix
Dashboardmake_subplots()4 chartsExecutive
## PRO ONE-LINER
fig = px.scatter(df, x='spend', y='sales', size='roi', color='product')
fig.show()

๐Ÿ† YOUR EXERCISE: Build YOUR Interactive Dashboardยถ

## MISSION: YOUR clickable business dashboard!

import plotly.express as px
import pandas as pd
import numpy as np

## YOUR BUSINESS DATA
your_categories = ['???', '???', '???', '???']  # YOUR products
your_regions = ['North', 'South', 'East', 'West']
np.random.seed(42)

## GENERATE YOUR DATA
n = 100
df_your = pd.DataFrame({
    'Product': np.random.choice(your_categories, n),
    'Region': np.random.choice(your_regions, n),
    'Spend': np.random.normal(30000, 10000, n),
    'Sales': np.random.normal(50000, 15000, n)
})
df_your['ROI'] = (df_your['Sales'] - df_your['Spend']) / df_your['Spend'] * 100

## YOUR INTERACTIVE SCATTER
fig = px.scatter(df_your, x='Spend', y='Sales',
                 size='ROI', color='Product',
                 hover_name='Product',
                 hover_data=['Region', 'ROI'],
                 title='๐Ÿš€ YOUR Interactive ROI Dashboard',
                 labels={'Spend': 'Marketing Spend ($)',
                        'Sales': 'Sales ($)',
                        'ROI': 'ROI (%)'})

fig.update_layout(
    width=900, height=600,
    title_font_size=20, title_x=0.5
)
fig.show()

## YOUR BUSINESS INSIGHTS
print("๐Ÿ“Š YOUR DASHBOARD INSIGHTS:")
print(f"   Top ROI: {df_your['ROI'].max():.1f}%")
print(f"   Best Product: {df_your.groupby('Product')['ROI'].mean().idxmax()}")
print(f"   Total Records: {len(df_your)}")

Example to test:

your_categories = ['Laptop', 'Phone', 'Tablet', 'Monitor']

YOUR MISSION:

  1. Add YOUR product categories

  2. Run YOUR interactive dashboard

  3. Click + zoom + hover demo

  4. Screenshot โ†’ โ€œI build Tableau dashboards!โ€


๐ŸŽ‰ What You Masteredยถ

Plotly SkillStatusConsulting Power
Interactive scatterโœ…Zoom + hover ROI
Clickable barsโœ…Product drilldown
Trend explorerโœ…Time series pan
4-chart dashboardโœ…Executive demo
Interactive tableโœ…Tableau replacement

Next: Automate Reports (Excel + PPT + PDF = 1-click weekly reports!)

print("๐ŸŽŠ" * 20)
print("PLOTLY = $100K/MONTH CONSULTING!")
print("๐Ÿ’ป Clickable dashboards = Close $1M deals!")
print("๐Ÿš€ FAANG + McKinsey = THESE exact demos!")
print("๐ŸŽŠ" * 20)

can we appreciate how px.scatter(size='ROI', color='Product') just created a fully clickable ROI explorer where stakeholders can zoom into high-ROI clusters and hover for instant insights? Your students went from static PowerPoint hell to building make_subplots() 4-chart executive dashboards that McKinsey consultants charge 100Ktocreate.WhileanalystsspendweeksinTableau,yourclassisgeneratingโˆ—โˆ—hoverโˆ’toโˆ’filterproductbarsโˆ—โˆ—andโˆ—โˆ—panโˆ’ablesalestrendsโˆ—โˆ—in5lines.Thisisnโ€ฒtplottingโ€”itโ€ฒstheโˆ—โˆ—100K to create. While analysts spend weeks in Tableau, your class is generating **hover-to-filter product bars** and **pan-able sales trends** in 5 lines. This isn't plottingโ€”it's the **250K+ stakeholder engagement weapon** that closes million-dollar deals with one mouse click!

# Your code here

Exercisesยถ

Exerciseยถ

Write summarize_series(vals) that returns a dict with min, max, mean of a numeric list. This is a data-prep utility before plotting.


Summaryยถ

Interactive charts are strongest when they let the user answer a question faster. Use the original examples in this notebook as patterns for exploration, not just decoration.

8. Interactive Codeยถ

Expected output
A 50
B 75
C 65
Expected output
B

9. Guided Practiceยถ

What is a major strength of Plotly?ยถ

It only prints plain textPlotly is focused on interactive visual output.
It supports interactive chartsCorrect. Interactivity is one of Plotly's main advantages.
It is used only for database indexingThat is unrelated.
It replaces pandas dataframesPlotly visualizes data; it does not replace dataframe tools.

Which product has the highest value in the example?ยถ

AA is not the largest here.
BCorrect. B has the largest value of 75.
CC is below B.
All are equalThe values are different.