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

การพลอตกราฟเส้นหลายเส้นด้วย Pandas และ Matplotlib

ใช้ df.pivot() จัดรูป DataFrame ให้ index เป็น x, columns เป็นชื่อสมการ, values เป็น y แล้วเรียก df.plot() จะพลอตทุกคอลัมน์เป็นเส้นแยกกันอัตโนมัติ

ขั้นตอนการทำงาน

  1. ตั้งค่าขนาดรูปและเลย์เอาต์
  2. สร้าง DataFrame คอลัมน์ equation, x, y
  3. Pivot table: df.pivot(index='x', columns='equation', values='y')
  4. พลอตด้วย df.plot()
  5. แสดงผล

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

import pandas as pd
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

df = pd.DataFrame([
    ["y=x^3", 0, 0], ["y=x^3", 1, 1], ["y=x^3", 2, 8], ["y=x^3", 3, 27], ["y=x^3", 4, 64],
    ["y=x^2", 0, 0], ["y=x^2", 1, 1], ["y=x^2", 2, 4], ["y=x^2", 3, 9], ["y=x^2", 4, 16],
    ["y=mx", 0, 0], ["y=mx", 1, 1], ["y=mx", 2, 2], ["y=mx", 3, 3], ["y=mx", 4, 3],
], columns=['equation', 'x', 'y'])

df = df.pivot(index='x', columns='equation', values='y')
df.plot()
plt.show()

ผลลัพธ์

การพลอตกราฟเส้นหลายเส้นด้วย Pandas และ Matplotlib