ภาพรวม
Pandas มีเมธอด plot() ในตัว สามารถพลอตหลาย DataFrame บน axes เดียวกันได้โดยส่งพารามิเตอร์ ax
ขั้นตอนการทำงาน
- กำหนดขนาดฟิกเกอร์
- สร้าง DataFrame 2 ตัว (df1, df2) ข้อมูลต่างกัน
- พลอต df1 ก่อน เก็บ axes ที่คืนมา
- พลอต df2 ส่ง
ax=axให้ใช้ axes เดียวกัน - แสดงผล
ตัวอย่างโค้ด
import pandas as pd
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
df1 = pd.DataFrame(dict(
name=['John', 'James', 'Stephen', 'Kandy'],
age=[23, 45, 12, 34]
))
df2 = pd.DataFrame(dict(
subject=['Math', 'Physics', 'Chemistry', 'Biology'],
marks=[67, 98, 90, 75]
))
ax = df1.plot(x='name', y='age')
df2.plot(ax=ax, x='subject', y='marks')
plt.show()
ผลลัพธ์
กราฟรวม 2 DataFrame บน axes เดียว (แกน X จะมีค่าผสมกัน)

หมายเหตุ
- เหมาะสำหรับข้อมูลที่มีแกน X เหมือนกัน (เช่น datetime index เดียวกัน)
- หากแกน X ต่างกัน ควรใช้ twinx() หรือ subplots แยก
- Pandas plot() เป็น wrapper ของ matplotlib ให้สะดวก