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

วิธีพล็อต 3 Dataset บนกราฟเดียวด้วย Matplotlib และ Python

Matplotlib: แพ็กเกจ Data Visualization ยอดนิยม Python สร้างกราฟ 2D Object-oriented API รองรับ IPython, Jupyter, Spyder บน NumPy

การติดตั้งและ Dependencies

pip install matplotlib
Python (>= 3.4), NumPy, Setuptools, Pyparsing, Libpng, Pytz, FreeType, Six, Cycler, Dateutil

ตัวอย่าง: พล็อต Linear, Quadratic, Cubic บนกราฟเดียว

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
x = np.linspace(0, 2, 100)
fig, ax = plt.subplots()

ax.plot(x, x, label='linear')
ax.plot(x, x**2, label='quadratic')
ax.plot(x, x**3, label='cubic')

ax.set_xlabel('x label name')
ax.set_ylabel('y label name')
ax.set_title("My Plot")
ax.legend()

ผลลัพธ์

วิธีพล็อต 3 Dataset บนกราฟเดียวด้วย Matplotlib และ Python

คำอธิบาย

  • นำเข้าแพ็กเกจและตั้งอเลียส
  • สร้าง Figure ว่างด้วย figure()
  • สร้างข้อมูล X ด้วย np.linspace
  • สร้าง Subplot ด้วย subplots()
  • พล็อต 3 Dataset ด้วย plot() พร้อม Label
  • ตั้งค่า Label แกน X, Y และ Title
  • แสดง Legend ด้วย ax.legend()