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

การพล็อตกราฟใน Python ด้วย Matplotlib

Python สามารถสร้างกราฟได้ผ่านไลบรารี matplotlib ซึ่งมีแพ็กเกจและฟังก์ชันมากมายสำหรับสร้างกราฟและพล็อตหลากหลายรูปแบบ การใช้งานก็ง่ายมาก โดยร่วมกับ numpy และฟังก์ชัน built-in ต่างๆ ของ Python ในบทความนี้จะแนะนำประเภทกราฟต่างๆ ที่สร้างได้

กราฟง่ายๆ (Simple Graphs)

ใช้ฟังก์ชันคณิตศาสตร์สร้างพิกัด x และ y แล้วพล็อตด้วย matplotlib พร้อมใส่ป้ายชื่อแกนและหัวข้อกราฟ ตัวอย่างพล็อตฟังก์ชันตรีโกณมิติ tan

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

from matplotlib import pyplot as plt
import numpy as np
import math

x = np.arange(0, math.pi*2, 0.05)
y = np.tan(x)
plt.plot(x, y)
plt.xlabel("angle")
plt.ylabel("Tan value")
plt.title('Tan wave')
plt.show()

ผลลัพธ์

การพล็อตกราฟใน Python ด้วย Matplotlib

หลายกราฟในพื้นที่เดียว (Multiplots)

สามารถสร้างหลายกราฟบน Canvas เดียวได้โดยสร้าง Axes หลายตัว

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

import matplotlib.pyplot as plt
import numpy as np
import math

x = np.arange(0, math.pi*2, 0.05)
fig = plt.figure()
axes1 = fig.add_axes([0.1, 0.1, 0.8, 0.8])  # แกนหลัก
axes2 = fig.add_axes([0.55, 0.55, 0.3, 0.3]) # แกนย่อย
axes3 = fig.add_axes([0.2, 0.3, 0.2, 0.3])   # แกนย่อย

axes1.plot(x, np.sin(x), 'b')
axes2.plot(x, np.cos(x), 'r')
axes3.plot(x, np.tan(x), 'g')
axes1.set_title('sine')
axes2.set_title('cosine')
axes3.set_title('tangent')
plt.show()

ผลลัพธ์

การพล็อตกราฟใน Python ด้วย Matplotlib

กริดของ Subplots

สร้างกริดที่มีหลาย Subplot โดยใช้ subplot2grid ต้องระบุตำแหน่งแกนให้พอดี

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

import matplotlib.pyplot as plt
import numpy as np

a1 = plt.subplot2grid((3,3), (0,0), colspan=2)
a2 = plt.subplot2grid((3,3), (0,2), rowspan=3)
a3 = plt.subplot2grid((3,3), (1,0), rowspan=2, colspan=2)

x = np.arange(1, 10)
a2.plot(x, x*x, 'r')
a2.set_title('square')
a1.plot(x, np.exp(x), 'b')
a1.set_title('exp')
a3.plot(x, np.log(x), 'g')
a3.set_title('log')
plt.tight_layout()
plt.show()

ผลลัพธ์

การพล็อตกราฟใน Python ด้วย Matplotlib

Contour Plot (กราฟเส้นระดับ)

แสดงผิว 3 มิติบนระนาบ 2 มิติ โดยใช้ X, Y เป็นตัวแปรพยากรณ์ และ Z เป็นตัวแปรตอบสนอง แสดงเป็นเส้นระดับ Matplotlib มี contour() และ contourf() สำหรับเส้นระดับและระดับที่เติมสี

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

import numpy as np
import matplotlib.pyplot as plt

xlist = np.linspace(-3.0, 3.0, 100)
ylist = np.linspace(-3.0, 3.0, 100)
X, Y = np.meshgrid(xlist, ylist)
Z = np.sqrt(X**2 + Y**2)

fig, ax = plt.subplots(1, 1)
cp = ax.contourf(X, Y, Z)
fig.colorbar(cp)
ax.set_title('Filled Contours Plot')
ax.set_ylabel('y (cm)')
plt.show()

ผลลัพธ์

การพล็อตกราฟใน Python ด้วย Matplotlib