最终可视化与报告导出
使用带注释图表构建多面板 Matplotlib 图形,导出为 PNG 和 PDF,并将结构化摘要写入 Markdown 文件
最终可视化与报告导出 是 CoddyKit 上的免费 Pandas & NumPy Academy 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Pandas & NumPy Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Pandas & NumPy Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
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

'''
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!
常见问题解答
「最终可视化与报告导出」课时是免费的吗?
是的 — 「最终可视化与报告导出」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Pandas & NumPy Academy 课程的其余内容,请升级到 CoddyKit PRO。 Pandas & NumPy Academy 课程共包含 4 节课。
「最终可视化与报告导出」这节课中我会学到什么?
使用带注释图表构建多面板 Matplotlib 图形,导出为 PNG 和 PDF,并将结构化摘要写入 Markdown 文件 你通过在浏览器中直接运行的动手代码来练习 Pandas & NumPy Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Pandas & NumPy Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Pandas & NumPy Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「最终可视化与报告导出」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Pandas & NumPy Academy 课中编写并运行代码吗?
能。每节 Pandas & NumPy Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 项目设置与数据导入
- 数据清洗与特征工程
- 分析与 KPI 计算
- 最终可视化与报告导出