Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การวาด Multiple Time-Series DataFrames บนกราฟเดียวด้วย Pandas และ Matplotlib

Pandas มีเมธอด plot() ในตัวที่ทำให้วาด Time-Series หลายชุดบนกราฟเดียวได้ง่าย รองรับ Secondary Y-axis สำหรับข้อมูลที่มقياسต่างกัน

ขั้นตอนหลัก

  1. สร้าง DataFrame พร้อม Datetime Index
  2. ใช้ df.plot() วาดหลายคอลัมน์พร้อมกัน
  3. ใช้ secondary_y สำหรับคอลัมน์ที่ต้องการแกน Y ด้านขวา
  4. จัดการ Legend ให้ชัดเจน

ตัวอย่างโค้ด

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [12, 6]
plt.rcParams["figure.autolayout"] = True

# สร้าง Time-Series DataFrame
dates = pd.date_range("2023-01-01", periods=100, freq="D")
df = pd.DataFrame({
    "Temperature": 25 + 5 * np.sin(np.arange(100) * 0.2) + np.random.randn(100) * 1.5,
    "Humidity": 60 + 15 * np.cos(np.arange(100) * 0.15) + np.random.randn(100) * 3,
    "Pressure": 1013 + np.random.randn(100) * 5,
    "Wind_Speed": 5 + 3 * np.sin(np.arange(100) * 0.3) + np.random.randn(100) * 1
}, index=dates)

# วาดกราฟหลายคอลัมน์พร้อมกัน
ax = df[["Temperature", "Humidity", "Pressure"]].plot(
    linewidth=1.5,
    alpha=0.8,
    colormap='Set1'
)

# เพิ่ม Wind_Speed บน Secondary Y-axis
ax2 = df["Wind_Speed"].plot(
    secondary_y=True,
    color='orange',
    linewidth=1.5,
    style='--',
    label="Wind Speed (m/s)",
    ax=ax
)

# จัดการ Legend รวม 2 แกน
lines1, labels1 = ax.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax.legend(lines1 + lines2, labels1 + labels2, loc='upper left', fontsize=11)

ax.set_xlabel("Date", fontsize=12)
ax.set_ylabel("Temp / Humidity / Pressure", fontsize=12)
ax2.set_ylabel("Wind Speed (m/s)", fontsize=12, color='orange')
ax.set_title("Weather Data: Multiple Time Series with Secondary Axis", fontsize=14, pad=15)
ax.grid(True, alpha=0.3)

plt.show()

ผลลัพธ์

กราฟเดียวแสดง 4 Time Series: Temperature, Humidity, Pressure บนแกน Y ซ้าย และ Wind Speed บนแกน Y ขวา (Secondary Axis) พร้อม Legend รวม

เทคนิคสำคัญ

  • DatetimeIndex: ต้องตั้ง Index เป็น Datetime เพื่อให้ Pandas จัดการแกน X อัตโนมัติ
  • secondary_y=True: สร้าง Twin Axis (ax.twinx()) อัตโนมัติ
  • ax.get_legend_handles_labels(): รวม Legend จาก 2 Axes
  • colormap: กำหนดชุดสีสำหรับหลายเส้นพร้อมกัน

ตัวอย่าง: แยก Subplots แทน Secondary Axis

# วาดแยก Subplots (เหมาะสำหรับมาตราสเกลต่างมาก)
fig, axes = plt.subplots(4, 1, figsize=(12, 10), sharex=True)
for i, col in enumerate(df.columns):
    df[col].plot(ax=axes[i], title=col, legend=False)
    axes[i].grid(True, alpha=0.3)
axes[-1].set_xlabel("Date")
plt.suptitle("Separate Subplots for Each Series", fontsize=16)
plt.tight_layout()
plt.show()