자동화된 차트 및 시각화 생성
matplotlib/seaborn 차트를 생성하고 base64 이미지 결과를 반환합니다.
자동화된 차트 및 시각화 생성은(는) CoddyKit의 무료 AI Agents 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 AI Agents 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. AI Agents 강의에는 총 4개의 강의가 포함되어 있습니다.
에이전트가 차트를 생성하는 이유
텍스트로 제시된 숫자는 이해하기 어렵습니다. 12개월 동안의 판매 추세를 보여 주는 차트는 숫자만 나열한 문단으로는 전달하기 어려운 내용을 몇 초 만에 보여 줍니다.
시각화를 생성할 수 있는 데이터 분석 에이전트는 훨씬 더 유용합니다. 사람이 분석할 때와 마찬가지로 숫자와 차트를 모두 제공합니다.
비대화형 Matplotlib 설정
기본적으로 matplotlib은 GUI 창을 엽니다. 화면이 없는 서버에서 실행되는 에이전트에서는 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산점도 생성
산점도는 두 수치 변수 사이의 관계를 드러냅니다. 예를 들어 광고 지출과 매출의 상관관계 또는 주문 규모와 배송 시간의 관계를 확인할 수 있습니다.
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이 차트에서 확인되는 핵심 통찰을 설명하는 한 문장 캡션을 생성하도록 합니다.
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)다중 Series 및 그룹 차트
여러 그룹을 비교할 때(예: 시간에 따른 지역별 매출) 그룹 차트 또는 다중 Series 차트를 사용합니다. Matplotlib은 하나의 그래프에 여러 선을 표시하고 오프셋을 적용한 그룹 막대 차트를 생성할 수 있습니다.
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 작성 캡션을 생성하여 차트를 만듭니다.
필수 차트 유형은 네 가지입니다. bar(범주 비교), line(시계열), scatter(추세선이 있는 상관관계), histogram(분포)입니다. 차트 유형 자동 선택을 사용하면 LLM이 데이터 특성과 사용자의 질문을 바탕으로 가장 적합한 시각화를 선택할 수 있습니다.
자주 묻는 질문
“자동화된 차트 및 시각화 생성” 강의는 무료인가요?
네 — “자동화된 차트 및 시각화 생성” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 AI Agents 강의 전체를 잠금 해제할 수 있습니다. AI Agents 강의에는 총 4개의 강의가 포함되어 있습니다.
“자동화된 차트 및 시각화 생성”에서 뭘 배우나요?
matplotlib/seaborn 차트를 생성하고 base64 이미지 결과를 반환합니다. 브라우저에서 직접 실행하는 실습 코드로 AI Agents을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
AI Agents을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 AI Agents은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“자동화된 차트 및 시각화 생성” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 AI Agents 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 AI Agents 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 데이터 분석을 위한 코드 인터프리터 패턴
- Pandas 기반 데이터 에이전트 도구
- 자동화된 차트 및 시각화 생성
- 통계 요약 에이전트