グラフと可視化の自動生成
matplotlibやseabornのグラフを生成し、画像結果をbase64で返します。
「グラフと可視化の自動生成」はCoddyKit上の無料AI Agentsレッスンです。 これはレッスン3/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはAI Agents学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 AI Agentsコースには全4レッスンが含まれています。
エージェントがグラフを生成する理由
文章中の数値は読み取りにくいものです。12か月間の売上傾向を示すグラフなら、数値を並べた段落では伝えられない内容を数秒で伝えられます。
可視化を生成できるデータ分析エージェントは、はるかに便利です。人間のアナリストと同じように、数値とグラフの両方を出力できるからです。
非対話型Matplotlibの設定
matplotlibはデフォルトでGUIウィンドウを開きます。表示環境のないサーバー側でエージェントを実行する場合は、Aggバックエンドに切り替える必要があります。AggバックエンドはGUIを使わず、ファイルにのみ描画します。
表示エラーを避けるため、pyplotをインポートする前に設定してください。
import matplotlib
matplotlib.use('Agg') # must be set BEFORE importing pyplot
import matplotlib.pyplot as plt
import os
OUTPUT_DIR = '/tmp/agent_charts'
os.makedirs(OUTPUT_DIR, exist_ok=True)
# Verify no display is needed
print('Backend:', matplotlib.get_backend()) # Should print: Agg棒グラフの生成
棒グラフは、カテゴリ間の値を比較するためのものです。上位N件のランキング、カテゴリ間の比較、実施前後の比較に使用します。
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import os
OUTPUT_DIR = '/tmp/agent_charts'
os.makedirs(OUTPUT_DIR, exist_ok=True)
def create_bar_chart(labels, values, title, xlabel, ylabel, filename):
fig, ax = plt.subplots(figsize=(10, 6))
bars = ax.bar(labels, values, color='steelblue', edgecolor='white')
# Add value labels on bars
for bar, value in zip(bars, values):
ax.text(
bar.get_x() + bar.get_width() / 2,
bar.get_height() + max(values) * 0.01,
f'{value:,.0f}', ha='center', va='bottom', fontsize=9
)
ax.set_title(title, fontsize=14, pad=15)
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
plt.xticks(rotation=45, ha='right')
plt.tight_layout()
path = os.path.join(OUTPUT_DIR, filename)
plt.savefig(path, dpi=150, bbox_inches='tight')
plt.close()
return path折れ線グラフの生成
折れ線グラフは、時間の経過に伴う傾向を示します。日次売上、月ごとのユーザー成長率、スプリントごとのパフォーマンス指標など、時系列データに使用します。
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import os
OUTPUT_DIR = '/tmp/agent_charts'
os.makedirs(OUTPUT_DIR, exist_ok=True)
def create_line_chart(x_values, y_values, title, xlabel, ylabel, filename, label=None):
fig, ax = plt.subplots(figsize=(10, 5))
ax.plot(x_values, y_values, marker='o', linewidth=2, markersize=5,
color='darkorange', label=label or ylabel)
# Highlight min and max points
max_idx = y_values.index(max(y_values))
min_idx = y_values.index(min(y_values))
ax.annotate(f'Max: {max(y_values):,.0f}',
xy=(x_values[max_idx], y_values[max_idx]),
xytext=(5, 10), textcoords='offset points', color='green')
ax.set_title(title, fontsize=14, pad=15)
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
ax.grid(True, alpha=0.3)
plt.xticks(rotation=45, ha='right')
plt.tight_layout()
path = os.path.join(OUTPUT_DIR, filename)
plt.savefig(path, dpi=150, bbox_inches='tight')
plt.close()
return path散布図の生成
散布図は、2つの数値変数間の関係を明らかにします。たとえば、広告費と収益の相関や、注文サイズと配送時間の関係を示せます。
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import os
OUTPUT_DIR = '/tmp/agent_charts'
os.makedirs(OUTPUT_DIR, exist_ok=True)
def create_scatter_chart(x_values, y_values, title, xlabel, ylabel, filename, add_trendline=True):
fig, ax = plt.subplots(figsize=(8, 6))
ax.scatter(x_values, y_values, alpha=0.6, color='royalblue', edgecolors='white', s=60)
if add_trendline and len(x_values) > 2:
z = np.polyfit(x_values, y_values, 1)
p = np.poly1d(z)
x_line = sorted(x_values)
ax.plot(x_line, p(x_line), 'r--', alpha=0.7, label='Trend')
ax.legend()
# Compute and show correlation
corr = np.corrcoef(x_values, y_values)[0, 1]
ax.text(0.05, 0.95, f'r = {corr:.2f}', transform=ax.transAxes,
fontsize=10, verticalalignment='top')
ax.set_title(title, fontsize=14, pad=15)
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
plt.tight_layout()
path = os.path.join(OUTPUT_DIR, filename)
plt.savefig(path, dpi=150, bbox_inches='tight')
plt.close()
return pathヒストグラムの生成
ヒストグラムは、単一の数値変数の分布を示します。注文金額の分布、顧客年齢の分布、応答時間の分布などに使用します。
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import os
OUTPUT_DIR = '/tmp/agent_charts'
os.makedirs(OUTPUT_DIR, exist_ok=True)
def create_histogram(values, title, xlabel, filename, bins=20):
fig, ax = plt.subplots(figsize=(8, 5))
n, bin_edges, patches = ax.hist(values, bins=bins, color='mediumseagreen',
edgecolor='white', alpha=0.8)
# Add mean and median lines
mean_val = np.mean(values)
median_val = np.median(values)
ax.axvline(mean_val, color='red', linestyle='--', label=f'Mean: {mean_val:.1f}')
ax.axvline(median_val, color='blue', linestyle='--', label=f'Median: {median_val:.1f}')
ax.set_title(title, fontsize=14, pad=15)
ax.set_xlabel(xlabel)
ax.set_ylabel('Frequency')
ax.legend()
plt.tight_layout()
path = os.path.join(OUTPUT_DIR, filename)
plt.savefig(path, dpi=150, bbox_inches='tight')
plt.close()
return pathエージェントの応答におけるBase64エンコード
グラフをPNGファイルとして保存した後、base64にエンコードします。これにより、ツールの結果としてJSONにシリアライズ可能な文字列で返せます。呼び出し元は、その文字列をレンダリングまたは表示できます。
import base64
def file_to_base64(filepath):
with open(filepath, 'rb') as f:
return base64.b64encode(f.read()).decode('utf-8')
def create_chart_result(chart_path, chart_type, caption):
b64 = file_to_base64(chart_path)
return {
'type': 'image',
'chart_type': chart_type,
'format': 'png',
'base64': b64,
'caption': caption,
'file_path': chart_path
}
# Usage after creating a chart
path = create_bar_chart(['Q1', 'Q2', 'Q3', 'Q4'], [12000, 15000, 18000, 22000],
'Quarterly Revenue', 'Quarter', 'Revenue ($)', 'revenue.png')
result = create_chart_result(path, 'bar', 'Quarterly revenue showing consistent growth')
print(f'Chart encoded: {len(result["base64"])} chars')キャプションの生成
キャプションのないグラフでは、閲覧者が自分で内容を解釈しなければなりません。LLMに、グラフから読み取れる重要な洞察を説明する1文のキャプションを生成させてください。
def generate_chart_caption(chart_type, data_summary, question):
prompt = f'''A {chart_type} chart was generated to answer: "{question}"
Data summary:
{data_summary}
Write a single clear sentence describing the most important insight shown in the chart.
Focus on the key finding, not on describing what type of chart it is.
Caption:'''
caption = llm_call(prompt).strip()
# Ensure it ends with a period
if caption and not caption.endswith('.'):
caption += '.'
return caption
# Example
caption = generate_chart_caption(
chart_type='bar',
data_summary='Q1: $12k, Q2: $15k, Q3: $18k, Q4: $22k (83% total growth)',
question='How did quarterly revenue trend this year?'
)
print(caption)
# -> "Revenue grew consistently each quarter, with Q4 nearly doubling Q1 figures."グラフ種別の自動選択
質問によって適したグラフの種類は異なります。使用するグラフをハードコードするのではなく、データの特性と質問の種類に基づいてLLMに決定させてください。
import json
CHART_TYPE_PROMPT = '''Choose the best chart type to answer this question.
Question: {question}
Data has columns: {columns}
Data sample: {sample}
Available chart types:
- bar: comparing values across categories
- line: trends over time
- scatter: relationship between two numeric variables
- histogram: distribution of one numeric variable
- pie: composition/proportions (use sparingly)
Return JSON: {{"chart_type": "bar", "x": "category_column", "y": "value_column",
"title": "Chart title", "xlabel": "X label", "ylabel": "Y label"}}'''
def select_chart_type(question, df):
sample = df.head(3).to_dict(orient='records')
response = llm_call(CHART_TYPE_PROMPT.format(
question=question,
columns=list(df.columns),
sample=json.dumps(sample, default=str)
))
return json.loads(response)統合グラフ生成ツール
すべてのグラフ種別を、エージェントが呼び出せる単一のツールにまとめます。ツールは、指定がない場合にグラフ種別を自動選択し、グラフを作成してエンコードし、キャプションを生成します。
import pandas as pd
def generate_chart(df_name, question, chart_type=None, filename=None):
df = dataframes.get(df_name)
if df is None:
return {'error': f'{df_name!r} not found'}
# Auto-select chart type if not specified
if not chart_type:
spec = select_chart_type(question, df)
else:
spec = {'chart_type': chart_type}
ct = spec.get('chart_type', 'bar')
x_col = spec.get('x', df.columns[0])
y_col = spec.get('y', df.select_dtypes(include='number').columns[0])
title = spec.get('title', question[:60])
fname = filename or f'chart_{ct}.png'
x_vals = df[x_col].tolist()
y_vals = df[y_col].tolist()
if ct == 'bar':
path = create_bar_chart(x_vals, y_vals, title, x_col, y_col, fname)
elif ct == 'line':
path = create_line_chart(x_vals, y_vals, title, x_col, y_col, fname)
elif ct == 'histogram':
path = create_histogram(y_vals, title, y_col, fname)
else:
path = create_scatter_chart(x_vals, y_vals, title, x_col, y_col, fname)
caption = generate_chart_caption(ct, f'{x_col} vs {y_col}', question)
return create_chart_result(path, ct, caption)複数系列グラフとグループ化グラフ
複数のグループ(たとえば、時間経過に伴う地域別の収益)を比較する場合は、グループ化グラフまたは複数系列グラフを使用します。Matplotlibでは、1つのプロットに複数の線を描画したり、位置をずらしたグループ化棒グラフを作成したりできます。
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import os
OUTPUT_DIR = '/tmp/agent_charts'
os.makedirs(OUTPUT_DIR, exist_ok=True)
def create_grouped_bar_chart(categories, series_data, title, xlabel, ylabel, filename):
n_groups = len(categories)
n_series = len(series_data)
bar_width = 0.8 / n_series
x = np.arange(n_groups)
fig, ax = plt.subplots(figsize=(12, 6))
colors = ['steelblue', 'darkorange', 'forestgreen', 'crimson']
for i, (label, values) in enumerate(series_data.items()):
offset = (i - (n_series - 1) / 2) * bar_width
ax.bar(x + offset, values, bar_width, label=label,
color=colors[i % len(colors)], alpha=0.85)
ax.set_xticks(x)
ax.set_xticklabels(categories, rotation=30, ha='right')
ax.set_title(title, fontsize=14, pad=15)
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
ax.legend()
plt.tight_layout()
path = os.path.join(OUTPUT_DIR, filename)
plt.savefig(path, dpi=150, bbox_inches='tight')
plt.close()
return path理解度チェック
サーバー側のエージェントでpyplotをインポートする前に、matplotlibのAggバックエンドを設定しなければならないのはなぜですか。
まとめ:自動グラフ・可視化生成
データエージェントは、matplotlibのAggバックエンドを設定(GUIなし)、plt.savefig()でグラフを作成、JSONで転送するためにbase64エンコード、LLMが重要な洞察を強調するキャプションを生成、という手順でグラフを生成します。
基本的なグラフの種類は4つあります。棒グラフ(カテゴリ比較)、折れ線グラフ(時系列)、散布図(トレンドラインを含む相関)、ヒストグラム(分布)です。グラフ種別の自動選択を使うと、LLMはデータの特性とユーザーの質問に基づいて最適な可視化を選べます。
よくある質問
「グラフと可視化の自動生成」レッスンは無料ですか?
はい。「グラフと可視化の自動生成」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、AI Agentsコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 AI Agentsコースには全4レッスンが含まれています。
「グラフと可視化の自動生成」で何を学びますか?
matplotlibやseabornのグラフを生成し、画像結果をbase64で返します。 ブラウザで直接実行するハンズオンコードでAI Agentsを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
AI Agentsを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのAI Agentsは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン3/4です。
「グラフと可視化の自動生成」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このAI Agentsレッスンでコードを書いて実行できますか?
はい。すべてのAI Agentsレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。