最終的な可視化とレポートのエクスポート
注釈付きのグラフを含む複数パネルのMatplotlib図を作成し、PNGとPDFにエクスポートして、構造化された概要をmarkdownファイルに書き出します。
「最終的な可視化とレポートのエクスポート」はCoddyKit上の無料Pandas & NumPy Academyレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはPandas & NumPy Academy学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Pandas & NumPy Academyコースには全4レッスンが含まれています。
最終成果物
キャップストーンプロジェクトの最後の段階では、計算したKPIを、共有しやすく完成度の高い成果物に仕上げます。具体的には、注釈付きグラフを含む複数パネルのMatplotlib図と、可視化への参照を埋め込んだ構造化されたMarkdownレポートを作成します。これが関係者に実際に渡すものです。明確なビジュアルと、分析結果をまとめた説明を提供します。優れた可視化は数値をインサイトに変え、優れたレポート構成はそのインサイトを行動につなげます。このレッスンでは、図の構成、注釈、PNG/PDFへの出力、構造化されたMarkdownの生成について扱います。
複数パネルの図を設定する
figsizeとgridspec_kwを指定したplt.subplots()を使って、サイズの異なるパネルを持つ図を作成します。経営層向けレポートでは、上部に幅の広い傾向グラフを配置し、下段に継続率ヒートマップと地域別棒グラフを配置するレイアウトがよく使われます。最初にplt.style.use('seaborn-v0_8-whitegrid')で一貫したスタイルを設定すると、各要素を手作業で書式設定しなくても、すっきりしたプロフェッショナルなグラフを作成できます。
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.')パネル1:月別売上の推移を示す折れ線グラフ
月間総売上をマーカー付きの折れ線で描画し、3か月移動平均を重ね、実績線の下の領域を塗りつぶします。ax.annotate()を使って、売上のピーク月と谷の月に矢印とテキストで注釈を付けます。これにより、売上が最も強かった時期、落ち込んだ時期、そして長期的な傾向が上向きかどうかを一目で伝えられます。実績値と平滑化した値を区別しつつ、互いに調和する色を使いましょう。
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()パネル2:コホート継続率ヒートマップ
Seabornを使い、コホート継続率マトリクスを色分けされたヒートマップとして可視化します。値を正規化し、100%(期間0)を最も明るい色にして、継続率が下がるにつれて段階的に暗くします。まだ発生していない将来期間のNaNセルにはマスクを適用し、グラフを見やすく保ちます。各セルにパーセント値を注記すると、値をすばやく読み取れます。このグラフは、顧客ロイヤルティのパターンを理解するうえで非常に役立つツールの1つです。
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()パネル3:上位地域の横棒グラフ
横棒グラフは、地域名(y軸のテキストラベル)を売上で比較するのに適しています。棒を降順に並べ、最も成績のよい地域を上に配置します。ax.text()を使って、各棒の末尾に売上値のラベルを追加します。売上構成比に基づく発散型カラーパレットを使い、上位地域には最も濃い色を割り当てます。このグラフにより、地理的な集中度と地域ごとのパフォーマンスをすぐに把握できます。
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()複数パネルの図を保存する
完成した図を2つの形式で出力します。プレゼンテーションやWebレポートへの埋め込みにはPNGを、高解像度の印刷にはPDFを使います。PNGではdpi=150以上を指定し、画面上でも図が鮮明に表示されるようにします。bbox_inches='tight'を渡すと、図の端でラベルが切れるのを防げます。プロジェクトの設定段階で作成した出力ディレクトリに保存します。
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')構造化されたMarkdownレポートを書く
構造化されたMarkdownファイルをプログラムで生成し、テキストレポートを作成します。ヘッダー、主要KPIを含むエグゼクティブサマリー、各分析セクションの主な発見、保存した図ファイルへの参照を含めます。手作業で書くのではなくコードからレポートを生成すれば、実際に計算された値を反映した新しく正確なレポートを、実行するたびに作成できます。Pythonのf-stringを使って、計算した数値をテキストに直接埋め込みます。
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')グラフに注釈を追加する
効果的なグラフは、注釈によってストーリーを伝えます。ax.axvline()で重要なイベント(製品の発売や価格変更など)を示し、ax.axhspan()で景気後退期を塗りつぶし、ax.annotate()で注目すべきデータポイントをテキストと矢印で示します。単位を付けて軸にラベルを設定し(ax.set_ylabel('Revenue ($)'))、説明的なタイトルを追加します。複数の系列を表示する場合は凡例を含め、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()データテーブルをExcelに出力する
関係者によっては、MarkdownレポートよりExcelを好む場合があります。pd.ExcelWriterを使うと、複数のDataFrameを1つのExcelブック内の異なるシートに出力できます。これは、データを自分で詳しく確認したいビジネス関係者向けの、プロフェッショナルな成果物です。startrowとstartcolを使ってシート内のテーブルの配置を調整し、最上位の数値をまとめた「Summary」シートを最初のタブとして追加します。
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')レポート生成を自動化する
データの取り込み、クリーニング、KPIの計算、可視化、レポートの出力というパイプライン全体を、コマンドラインから実行できるmain()関数にまとめます。Pythonのloggingモジュールを使って、開始時刻と終了時刻、各段階の行数、検出された異常を記録します。python pipeline.pyという1つのコマンドで最初から最後まで実行できるパイプラインは、cron、Airflow、またはクラウドスケジューラによるスケジュール自動化に対応できます。
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()コースの修了と次のステップ
データ分析:Pandas & NumPyトラックを修了しました。これで、ブロードキャストと線形代数を使ったNumPy配列の作成・変換、あらゆるデータソースからのPandas DataFrameの構築・操作、実世界のデータセットのクリーニング・再形成・集計、MatplotlibとSeabornによる出版品質の可視化、SciPyによる統計検定、大規模データセットへのチャンク処理とDaskの適用、PandasとSQLデータベースの連携、再現可能なエンドツーエンドのデータパイプラインの設計ができるようになりました。これらのスキルは、業界のあらゆるデータ活用職種の基礎となります。
クイックチェック
このレッスンで学んだデータ分析の概念について、理解度を確認しましょう。
レッスンのまとめ
この最後のレッスンでは、GridSpecを使った複数パネルのMatplotlib図によって複数のグラフ形式を組み合わせたプロフェッショナルなレポートレイアウトを実現する方法、注釈(axvline、annotate、text)によってグラフに説明の文脈を加える方法、そしてmain()関数内でのレポート生成の自動化(Markdown、Excel、PNG、PDF)によってパイプラインをスケジュール実行可能かつ再現可能にする方法を学びました。PandasとNumPyのトラック修了、おめでとうございます。これで実世界のデータ分析課題に取り組む準備が整いました。
AI チューターと学ぶ Python — 無料
ブラウザでリアルコードを書いて実行し、24/7 の AI チューターから瞬時にサポートを受け、ウェブまたはアプリで続きから学習できます。
- コース
- 30
- レッスン
- 120
よくある質問
「最終的な可視化とレポートのエクスポート」レッスンは無料ですか?
はい。「最終的な可視化とレポートのエクスポート」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Pandas & NumPy Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Pandas & NumPy Academyコースには全4レッスンが含まれています。
「最終的な可視化とレポートのエクスポート」で何を学びますか?
注釈付きのグラフを含む複数パネルのMatplotlib図を作成し、PNGとPDFにエクスポートして、構造化された概要をmarkdownファイルに書き出します。 ブラウザで直接実行するハンズオンコードでPandas & NumPy Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
Pandas & NumPy Academyを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのPandas & NumPy Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン4/4です。
「最終的な可視化とレポートのエクスポート」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このPandas & NumPy Academyレッスンでコードを書いて実行できますか?
はい。すべてのPandas & NumPy Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- プロジェクトのセットアップとデータ取り込み
- データクリーニングと特徴量エンジニアリング
- 分析とKPIの計算
- 最終的な可視化とレポートのエクスポート