Fatskills
Practice. Master. Repeat.
Study Guide: TECH **Python for Data Science: Dashboard-Ready Visuals & Exporting to HTML/PNG**
Source: https://www.fatskills.com/data-science/chapter/tech-python-for-data-science-dashboard-ready-visuals-exporting-to-htmlpng

TECH **Python for Data Science: Dashboard-Ready Visuals & Exporting to HTML/PNG**

By Fatskills Exam Guides Team — the exam nerds behind 28,500+ quizzes and 2.1M practice questions across 500+ global exams.

⏱️ ~7 min read

Python for Data Science: Dashboard-Ready Visuals & Exporting to HTML/PNG

Hyper-practical, zero-fluff guide for production-grade visuals


1. What This Is & Why It Matters

You’re a data scientist or analyst, and your boss just asked for a shareable, interactive dashboard—not a Jupyter notebook. Or maybe you’re prepping for a certification (PL-300, DP-100) and need to export visuals programmatically for reports, emails, or web apps.

Why this matters in production:
- Static exports (PNG/PDF) are required for emails, PowerPoint decks, or printed reports.
- Interactive HTML lets stakeholders explore data without Python (e.g., sales teams, executives).
- Automation (e.g., cron jobs, Airflow) needs headless rendering—no GUI, no manual clicks.
- Reproducibility breaks if you rely on Jupyter’s "Save As" button. You need code-controlled exports.

Real-world scenario:
You built a matplotlib/seaborn dashboard in a notebook. Now: - The marketing team wants a PNG for their weekly email.
- The CFO wants an interactive HTML to drill into sales data.
- Your CI/CD pipeline needs to auto-generate reports when new data arrives.

If you don’t know how to export programmatically, you’re stuck manually screenshotting—or worse, rewriting everything in Tableau.


2. Core Concepts & Components


1. matplotlib

  • What it is: The foundational Python plotting library (like Excel charts, but code-controlled).
  • Production insight: Default styles look dated. Use plt.style.use('seaborn') or plt.rcParams to match corporate branding.

2. seaborn

  • What it is: High-level wrapper for matplotlib (e.g., sns.barplot() vs. plt.bar()).
  • Production insight: Always set sns.set_theme(context='talk') for dashboard-ready sizing.

3. plotly / plotly.express

  • What it is: Interactive, web-ready visuals (hover tooltips, zoom, pan).
  • Production insight: Use fig.write_html("dashboard.html", include_plotlyjs='cdn') to avoid bloating file size.

4. altair

  • What it is: Declarative JSON-based plotting (great for Vega-Lite integration).
  • Production insight: Export with chart.save('chart.html')—but it’s not interactive by default.

5. kaleido (for plotly)

  • What it is: Headless image export engine (no browser needed).
  • Production insight: Install with pip install -U kaleidorequired for fig.write_image() in CI/CD.

6. selenium / playwright (for dynamic exports)

  • What it is: Browser automation to capture JavaScript-rendered plots (e.g., plotly in a Flask app).
  • Production insight: Overkill for most cases—use kaleido first.

7. weasyprint / pdfkit

  • What it is: Convert HTML/CSS to PDF (e.g., matplotlib → HTML → PDF).
  • Production insight: weasyprint is lighter than pdfkit (no Chrome dependency).

8. nbconvert

  • What it is: Convert Jupyter notebooks to HTML/PDF/PNG.
  • Production insight: Use --no-input to hide code cells in reports.


3. Step-by-Step: Exporting Visuals Like a Pro


Prerequisites

  • Python 3.8+ (use pyenv if needed).
  • Libraries: pip install matplotlib seaborn plotly kaleido pandas nbconvert weasyprint.
  • For plotly PNGs: pip install -U kaleido (critical for headless rendering).


Task 1: Export a matplotlib Plot to PNG

Goal: Generate a sales trend plot and save it as sales_trend.png.


import matplotlib.pyplot as plt
import pandas as pd

# Sample data
data = pd.DataFrame({
'month': ['Jan', 'Feb', 'Mar', 'Apr'],
'sales': [1200, 1500, 1800, 2200] }) # Plot plt.figure(figsize=(10, 6)) plt.plot(data['month'], data['sales'], marker='o', linewidth=3) plt.title("Monthly Sales Trend", fontsize=16, pad=20) plt.xlabel("Month", fontsize=12) plt.ylabel("Sales ($)", fontsize=12) plt.grid(True, linestyle='--', alpha=0.6) # Save as PNG (300 DPI for print quality) plt.savefig(
"sales_trend.png",
dpi=300, # High resolution
bbox_inches='tight', # No cropped labels
facecolor='white' # White background (not transparent) ) plt.close() # Free memory

Verify:


ls -lh sales_trend.png  # Should be ~100KB
file sales_trend.png    # Should show "PNG image data"


Task 2: Export an Interactive plotly Dashboard to HTML

Goal: Create a plotly scatter plot and save it as interactive_dashboard.html.


import plotly.express as px
import pandas as pd

# Sample data
df = pd.DataFrame({
'product': ['A', 'B', 'C', 'D'],
'sales': [1200, 1500, 800, 2000],
'profit': [300, 450, 200, 600] }) # Create interactive plot fig = px.scatter(
df,
x='sales',
y='profit',
color='product',
title="Sales vs. Profit (Interactive)",
hover_data=['product'] ) # Save as HTML (use CDN to reduce file size) fig.write_html(
"interactive_dashboard.html",
include_plotlyjs='cdn', # Load JS from CDN (smaller file)
full_html=False # Embed as a <div> (for web apps) )

Verify:


ls -lh interactive_dashboard.html  # Should be <50KB
# Open in browser: python -m http.server 8000


Task 3: Convert a Jupyter Notebook to a Report (HTML/PDF)

Goal: Export a notebook to a clean HTML report (no code cells).


# Convert notebook to HTML (hide code)
jupyter nbconvert --to html \
--no-input \ # Hide code cells
--no-prompt \ # Hide prompts (In [1]:)
--output report.html \
analysis.ipynb # Convert to PDF (requires LaTeX or weasyprint) jupyter nbconvert --to pdf --no-input analysis.ipynb # OR (if LaTeX fails) weasyprint report.html report.pdf

Verify:


ls -lh report.html report.pdf


Task 4: Automate PNG Exports in a Script (Headless Mode)

Goal: Generate a plotly PNG in a CI/CD pipeline (no GUI).


import plotly.express as px
import pandas as pd

df = pd.DataFrame({
'x': [1, 2, 3, 4],
'y': [10, 11, 12, 13] }) fig = px.line(df, x='x', y='y', title="Automated PNG Export") fig.write_image(
"ci_plot.png",
scale=2, # 2x resolution
width=800, # Fixed width
height=500 # Fixed height )

Verify in CI:


# In GitHub Actions / GitLab CI:
file ci_plot.png  # Should show "PNG image data"


4. ? Production-Ready Best Practices


Security

  • Never hardcode paths: Use os.path.join() or pathlib.Path.
  • Sanitize filenames: Strip spaces/special chars (e.g., filename = re.sub(r'[^\w\-_]', '_', title)).
  • Avoid eval() in dynamic plots: Use json.loads() for config.

Cost Optimization

  • Use include_plotlyjs='cdn' to reduce HTML file size.
  • Compress PNGs: pip install pillow + Image.save('plot.png', optimize=True).
  • Cache exports: Store generated files in S3 with lifecycle policies.

Reliability & Maintainability

  • Set explicit figsize/width/height to avoid layout shifts.
  • Use bbox_inches='tight' in matplotlib to prevent cropped labels.
  • Version exports: Append timestamps (e.g., report_20231015.html).

Observability

  • Log export failures: Wrap fig.write_image() in a try/except.
  • Monitor file sizes: Alert if report.html > 5MB (indicates bloat).


5. ⚠️ Common Mistakes & Traps

Mistake Symptom Fix/Prevention
Not installing kaleido fig.write_image() fails in CI/CD pip install -U kaleido
Using plt.show() before savefig() Blank PNGs Call plt.savefig() before plt.show()
Default matplotlib styles Ugly, unbranded plots plt.style.use('seaborn') or custom rcParams
bbox_inches='tight' missing Cropped axis labels Always add bbox_inches='tight' to savefig()
plotly HTML too large 10MB+ files Use include_plotlyjs='cdn'


6. ? Exam/Certification Focus

Typical question patterns:
1. "Which library exports interactive HTML?"
- ❌ matplotlib (static only)
- ✅ plotly (interactive)
- ❌ seaborn (static)


  1. "How do you save a plotly figure as PNG in a script?"
  2. fig.write_image("plot.png") (requires kaleido)
  3. fig.show() (opens browser, not headless)

  4. "What’s the best way to hide code in a Jupyter report?"

  5. jupyter nbconvert --no-input
  6. ❌ Manually delete cells (not reproducible)

Trap distinctions:
- matplotlib vs. plotly: - matplotlib: Static, lightweight, good for PDFs.
- plotly: Interactive, heavier, good for web dashboards.


7. ? Hands-On Challenge

Task: Export a seaborn heatmap to PNG with a white background and 300 DPI.

Solution:


import seaborn as sns
import matplotlib.pyplot as plt

data = sns.load_dataset("flights").pivot("month", "year", "passengers")
plt.figure(figsize=(10, 8))
sns.heatmap(data, annot=True, fmt="d", cmap="YlGnBu")
plt.title("Passenger Traffic Heatmap")
plt.savefig(
"heatmap.png",
dpi=300,
bbox_inches='tight',
facecolor='white' ) plt.close()

Why it works:
- facecolor='white' ensures the background isn’t transparent.
- dpi=300 guarantees print-quality resolution.


8. ? Rapid-Reference Crib Sheet

Task Command/Code Notes
Save matplotlib to PNG plt.savefig("plot.png", dpi=300, bbox_inches='tight') Always set dpi and bbox_inches.
Save plotly to HTML fig.write_html("plot.html", include_plotlyjs='cdn') Use CDN to reduce file size.
Save plotly to PNG fig.write_image("plot.png", scale=2) Requires kaleido.
Convert notebook to HTML jupyter nbconvert --to html --no-input notebook.ipynb Hides code cells.
Convert HTML to PDF weasyprint report.html report.pdf No LaTeX dependency.
Set matplotlib style plt.style.use('seaborn') Corporate-friendly.
⚠️ Default matplotlib DPI dpi=100 (too low for print) Always override.
⚠️ plotly HTML bloat include_plotlyjs=True (default) Use cdn instead.


9. ? Where to Go Next

  1. Matplotlib Tutorial – Official docs for advanced styling.
  2. Plotly Python Docs – Interactive visuals guide.
  3. WeasyPrint Docs – HTML-to-PDF conversion.
  4. Seaborn Gallery – Copy-paste templates.


ADVERTISEMENT