0Pricing
Pandas & NumPy Academy · Lesson

Final Visualisation and Report Export

Build a multi-panel Matplotlib figure with annotated charts, export to PNG and PDF, and write a structured summary to a markdown file.

Final Visualisation and Report Export is a free Pandas & NumPy Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Pandas & NumPy Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

The Final Deliverable

The last stage of the capstone turns computed KPIs into a polished, shareable deliverable: a multi-panel Matplotlib figure with annotated charts and a structured markdown report with embedded visualisation references. This is what stakeholders actually receive — clear visuals and a narrative summary. Good visualisation transforms numbers into insights; good report structure makes those insights actionable. This lesson covers figure architecture, annotation, export to PNG/PDF, and structured markdown generation.

Setting Up the Multi-Panel Figure

Use plt.subplots() with figsize and gridspec_kw to create a figure with panels of different sizes. A common executive report layout: a wide trend chart on top, a retention heatmap and region bar chart on the bottom row. Set a consistent style upfront with plt.style.use('seaborn-v0_8-whitegrid') to get clean, professional-looking charts without manual formatting of each element.

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

plt.style.use('seaborn-v0_8-whitegrid')

# 2x2 layout with custom row heights
fig = plt.figure(figsize=(16, 12))
gs = gridspec.GridSpec(2, 2,
                       height_ratios=[1, 1.2],
                       hspace=0.4, wspace=0.35)

ax_trend   = fig.add_subplot(gs[0, :])   # full width top row
ax_heatmap = fig.add_subplot(gs[1, 0])   # bottom left
ax_bar     = fig.add_subplot(gs[1, 1])   # bottom right

print('Figure with 3 panels created.')

Panel 1: Monthly Revenue Trend Line

Plot total monthly revenue as a line with markers, overlay a 3-month rolling average, and shade the area under the actual line. Annotate the peak and trough months with arrows and text using ax.annotate(). This tells the story instantly: where revenue was strongest, where it dipped, and whether the long-term trend is positive. Use colours that distinguish actual from smoothed without clashing.

import pandas as pd
import matplotlib.pyplot as plt

monthly = pd.read_parquet('output/kpi_monthly_category_revenue.parquet')
monthly_total = monthly.sum(axis=1)

ax = plt.gca()
ax.plot(monthly_total.index, monthly_total.values,
        marker='o', linewidth=2, color='#2196F3', label='Monthly Revenue')
ax.plot(monthly_total.index,
        monthly_total.rolling(3, min_periods=1).mean().values,
        linewidth=2, linestyle='--', color='#FF5722', label='3-Month Avg')
ax.fill_between(monthly_total.index, monthly_total.values, alpha=0.1, color='#2196F3')

# Annotate peak
peak_idx = monthly_total.idxmax()
ax.annotate(f'Peak: ${monthly_total[peak_idx]/1e3:.0f}K',
            xy=(peak_idx, monthly_total[peak_idx]),
            xytext=(0, 20), textcoords='offset points',
            arrowprops=dict(arrowstyle='->', color='#E91E63'),
            color='#E91E63', fontsize=10)
ax.set_title('Monthly Revenue Trend', fontsize=14, fontweight='bold')
ax.legend()
plt.show()

Panel 2: Cohort Retention Heatmap

Visualise the cohort retention matrix as a colour-coded heatmap using Seaborn. Normalise values so that 100% (period 0) is the brightest colour and declining retention is progressively darker. Mask NaN cells (future periods that have not occurred yet) to keep the chart clean. Annotate each cell with the percentage value for quick reading. This chart is one of the most valuable tools for understanding customer loyalty patterns.

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

retention = pd.read_parquet('output/kpi_cohort_retention.parquet')

fig, ax = plt.subplots(figsize=(10, 6))

sns.heatmap(
    retention,
    annot=True,
    fmt='.0%',
    cmap='YlOrRd_r',
    mask=retention.isna(),
    linewidths=0.5,
    ax=ax,
    cbar_kws={'label': 'Retention Rate'}
)
ax.set_title('Cohort Retention Matrix', fontsize=14, fontweight='bold')
ax.set_xlabel('Months After First Purchase')
ax.set_ylabel('Cohort Month')
plt.tight_layout()
plt.show()

Panel 3: Top Regions Horizontal Bar Chart

A horizontal bar chart is ideal for comparing region names (text labels on the y-axis) by revenue. Sort bars in descending order so the best region is at the top. Add revenue value labels at the end of each bar using ax.text(). Use a diverging colour palette based on revenue share — the top region gets the deepest colour. This chart immediately communicates geographic concentration and regional performance.

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np

region_kpi = pd.read_parquet('output/kpi_region_summary.parquet')
top5 = region_kpi.head(5).sort_values('total_revenue')

fig, ax = plt.subplots(figsize=(8, 5))
colors = cm.Blues(np.linspace(0.4, 0.9, len(top5)))

bars = ax.barh(top5['region'], top5['total_revenue'], color=colors)
for bar, val in zip(bars, top5['total_revenue']):
    ax.text(bar.get_width() * 1.01, bar.get_y() + bar.get_height()/2,
            f'${val/1e3:.0f}K', va='center', fontsize=9)

ax.set_title('Top 5 Regions by Revenue', fontsize=13, fontweight='bold')
ax.set_xlabel('Total Revenue ($)')
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
plt.tight_layout()
plt.show()

Saving the Multi-Panel Figure

Export the completed figure in two formats: PNG for embedding in presentations and web reports, and PDF for high-resolution print. Use dpi=150 or higher for PNG to ensure the figure is sharp at screen resolution. Pass bbox_inches='tight' to avoid clipping labels at the figure edge. Save to the output directory established in the project setup stage.

import matplotlib.pyplot as plt

# After assembling all panels in the figure
fig.suptitle('2024 Sales Performance Report', fontsize=16,
             fontweight='bold', y=1.02)

# Save as PNG (for web/presentations)
fig.savefig('output/report_figure.png',
            dpi=150,
            bbox_inches='tight',
            facecolor='white')

# Save as PDF (for print)
fig.savefig('output/report_figure.pdf',
            bbox_inches='tight',
            facecolor='white')

print('Figures saved:')
print('  output/report_figure.png')
print('  output/report_figure.pdf')

Writing the Structured Markdown Report

Generate the text report by writing a structured markdown file programmatically. Include a header, executive summary with top-line KPIs, key findings from each analysis section, and references to the saved figure files. By generating the report from code rather than writing it manually, every run produces a fresh, accurate report reflecting the actual computed values. Use Python f-strings to embed computed numbers directly into the text.

import pandas as pd
from datetime import datetime

df = pd.read_parquet('output/analysis_ready.parquet')
region_kpi = pd.read_parquet('output/kpi_region_summary.parquet')
retention = pd.read_parquet('output/kpi_cohort_retention.parquet')

report = f'''
# 2024 Sales Performance Report

Generated: {datetime.now().strftime('%Y-%m-%d %H:%M')}

## Executive Summary

- **Total Revenue**: ${df['revenue'].sum():,.0f}
- **Total Orders**: {df['order_id'].nunique():,}
- **Unique Customers**: {df['customer_id'].nunique():,}
- **Top Region**: {region_kpi.iloc[0]['region']} (${region_kpi.iloc[0]['total_revenue']:,.0f})
- **Average Month-3 Retention**: {retention.get(3, pd.Series([0])).mean():.1%}

## Key Findings

1. Revenue grew steadily through the year with a peak in October.
2. The top region accounts for {region_kpi.iloc[0]['revenue_share']:.0%} of total revenue.
3. Month-3 cohort retention averages {retention.get(3, pd.Series([0])).mean():.1%}.

## Figures

![Revenue Trends](report_figure.png)
'''
with open('output/report.md', 'w') as f:
    f.write(report)
print('Report written to output/report.md')

Adding Annotations to Charts

Effective charts tell a story through annotations. Use ax.axvline() to mark important events (a product launch, a pricing change), ax.axhspan() to shade recession periods, and ax.annotate() to call out notable data points with text and arrows. Label the axes with units (ax.set_ylabel('Revenue ($)')), add a descriptive title, include a legend when multiple series are shown, and format tick labels for readability using ax.yaxis.set_major_formatter(FuncFormatter(...)).

import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import pandas as pd

monthly_total = pd.read_parquet('output/kpi_monthly_category_revenue.parquet').sum(axis=1)

fig, ax = plt.subplots(figsize=(12, 5))
ax.plot(monthly_total.index, monthly_total.values, linewidth=2.5, color='#1565C0')

# Format y-axis as $K
ax.yaxis.set_major_formatter(
    mticker.FuncFormatter(lambda x, _: f'${x/1e3:.0f}K')
)

# Mark a hypothetical event
ax.axvline(x='2024-06', color='red', linestyle=':', alpha=0.6)
ax.text('2024-06', monthly_total.max() * 0.95,
        ' Campaign\n Launch', color='red', fontsize=9)

ax.set_title('Monthly Revenue 2024', fontsize=14, fontweight='bold')
ax.set_xlabel('Month')
ax.set_ylabel('Revenue')
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

Exporting Data Tables to Excel

Some stakeholders prefer Excel over markdown reports. Use pd.ExcelWriter to export multiple DataFrames to different sheets in a single Excel workbook. This is a professional deliverable for business stakeholders who want to explore the data themselves. Use startrow and startcol to arrange tables within a sheet, and add a 'Summary' sheet with top-level numbers as the first tab.

import pandas as pd

region_kpi = pd.read_parquet('output/kpi_region_summary.parquet')
retention = pd.read_parquet('output/kpi_cohort_retention.parquet')
product_rank = pd.read_parquet('output/kpi_product_ranking.parquet')

with pd.ExcelWriter('output/sales_report_2024.xlsx', engine='openpyxl') as writer:
    region_kpi.to_excel(writer, sheet_name='Region KPIs', index=False)
    retention.to_excel(writer, sheet_name='Cohort Retention')
    product_rank.head(50).to_excel(writer, sheet_name='Top 50 Products', index=False)

print('Excel workbook written: output/sales_report_2024.xlsx')

Automating Report Generation

Wrap the entire pipeline — ingestion, cleaning, KPI computation, visualisation, and report export — in a main() function that can be executed from the command line. Use Python's logging module to record start and end times, row counts at each stage, and any anomalies detected. A pipeline that runs end-to-end with a single python pipeline.py command is ready for scheduled automation via cron, Airflow, or a cloud scheduler.

import logging
import time
from datetime import datetime

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s [%(levelname)s] %(message)s'
)

def main():
    start = time.time()
    logging.info('Pipeline started')

    logging.info('Step 1: Data ingestion')
    # load_and_merge()  # returns df

    logging.info('Step 2: Data cleaning')
    # clean(df)  # returns df_clean

    logging.info('Step 3: KPI computation')
    # compute_kpis(df_clean)  # saves parquet files

    logging.info('Step 4: Visualisation and report export')
    # build_report()  # saves PNG, PDF, markdown, Excel

    elapsed = time.time() - start
    logging.info(f'Pipeline complete in {elapsed:.1f}s')

if __name__ == '__main__':
    main()

Course Completion and Next Steps

You have completed the Data Analysis: Pandas & NumPy track. You can now: create and transform NumPy arrays with broadcasting and linear algebra, build and manipulate Pandas DataFrames from any data source, clean, reshape, and aggregate real-world datasets, create publication-quality visualisations with Matplotlib and Seaborn, apply statistical tests with SciPy, scale to large datasets with chunking and Dask, integrate Pandas with SQL databases, and design reproducible end-to-end data pipelines. These skills are the foundation of every data-driven role in industry.

Quick Check

Test your understanding of Data Analysis concepts from this lesson.

Lesson Recap

In this final lesson you learned: multi-panel Matplotlib figures with GridSpec enable professional report layouts combining multiple chart types, annotations (axvline, annotate, text) add narrative context to charts, and automated report generation (markdown, Excel, PNG, PDF) in a main() function makes the pipeline schedulable and reproducible. Congratulations on completing the Pandas and NumPy track — you are ready to tackle real-world data analysis challenges!

Frequently asked questions

Is the “Final Visualisation and Report Export” lesson free?

Yes — the full text of “Final Visualisation and Report Export” is free to read here on the web, and the Pandas & NumPy Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Pandas & NumPy Academy course, upgrade to CoddyKit PRO.

What will I learn in “Final Visualisation and Report Export”?

Build a multi-panel Matplotlib figure with annotated charts, export to PNG and PDF, and write a structured summary to a markdown file. You practise Pandas & NumPy Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Pandas & NumPy Academy?

No prior experience is required. Pandas & NumPy Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Final Visualisation and Report Export” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Pandas & NumPy Academy lesson?

Yes. Every Pandas & NumPy Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Project Setup and Data Ingestion
  2. Data Cleaning and Feature Engineering
  3. Analysis and KPI Computation
  4. Final Visualisation and Report Export
← Back to Pandas & NumPy Academy