0Pricing
AI Agents · บทเรียน

การสร้างแผนภูมิและภาพข้อมูลอัตโนมัติ

สร้างแผนภูมิ matplotlib/seaborn และส่งคืนผลลัพธ์ภาพแบบ base64

การสร้างแผนภูมิและภาพข้อมูลอัตโนมัติ เป็นบทเรียน AI Agents ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน 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)

แผนภูมิหลายชุดข้อมูลและแบบจัดกลุ่ม

เมื่อต้องเปรียบเทียบหลายกลุ่ม (เช่น รายได้ตามภูมิภาคในแต่ละช่วงเวลา) ให้ใช้แผนภูมิแบบจัดกลุ่มหรือแบบหลายชุดข้อมูล 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

ตรวจสอบความเข้าใจ

เหตุใดจึงต้องตั้งค่าแบ็กเอนด์ Agg ของ matplotlib ก่อนนำเข้า pyplot ในเอเจนต์ฝั่งเซิร์ฟเวอร์

สรุป: การสร้างแผนภูมิและภาพข้อมูลอัตโนมัติ

เอเจนต์ข้อมูลสร้างแผนภูมิโดยตั้งค่าแบ็กเอนด์ Agg ของ matplotlib (ไม่ใช้ GUI) สร้างแผนภูมิด้วย plt.savefig() เข้ารหัสเป็นbase64เพื่อส่งผ่าน JSON และสร้างคำบรรยายจาก LLM ที่เน้นข้อค้นพบสำคัญ

ประเภทแผนภูมิสำคัญ 4 ประเภท ได้แก่ bar (การเปรียบเทียบหมวดหมู่) line (อนุกรมเวลา) scatter (ความสัมพันธ์พร้อมเส้นแนวโน้ม) และ histogram (การกระจาย) การเลือกประเภทแผนภูมิอัตโนมัติทำให้ LLM เลือกภาพข้อมูลที่เหมาะสมที่สุดตามลักษณะของข้อมูลและคำถามของผู้ใช้

คำถามที่พบบ่อย

บทเรียน “การสร้างแผนภูมิและภาพข้อมูลอัตโนมัติ” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การสร้างแผนภูมิและภาพข้อมูลอัตโนมัติ” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส AI Agents ให้อัปเกรดเป็น CoddyKit PRO คอร์ส AI Agents มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การสร้างแผนภูมิและภาพข้อมูลอัตโนมัติ”

สร้างแผนภูมิ matplotlib/seaborn และส่งคืนผลลัพธ์ภาพแบบ base64 คุณปฏิบัติ AI Agents ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน AI Agents หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน AI Agents บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน

บทเรียน “การสร้างแผนภูมิและภาพข้อมูลอัตโนมัติ” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน AI Agents นี้ได้ไหม

ได้ บทเรียน AI Agents ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. รูปแบบตัวแปลโค้ดสำหรับการวิเคราะห์ข้อมูล
  2. เครื่องมือตัวแทนขับเคลื่อนด้วย Pandas
  3. การสร้างแผนภูมิและภาพข้อมูลอัตโนมัติ
  4. ตัวแทนสรุปผลทางสถิติ
← กลับไปที่ AI Agents