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

วิธาสร้างกราฟสองกราฟวางติดกันด้วย Python


โดยใช้เมธอด subplot(row, col, index) เราสามารถแบ่งรูปเป็น row*col ส่วน และวาดกราฟที่ตำแหน่ง index ในโปรแกรมนี้ เราจะสร้างสองแผนภูมิในรูปเดียว

ขั้นตอน

  • สร้างจุด x, y1, y2 โดยใช้ numpy

  • ด้วย nrows = 1, ncols = 2, index = 1 เพิ่ม subplot ให้กับรูปปัจจุบันโดยใช้เมธอด subplot()

  • วาดเส้นโดยใช้จุด x และ y1 ด้วยเมธอด plot()

  • ตั้งค่าชื่อเรื่อง ป้ายกำกับแกน X และ Y สำหรับกราฟที่ 1 โดยใช้ plt.title(), plt.xlabel() และ plt.ylabel()

  • ด้วย nrows = 1, ncols = 2, index = 2 เพิ่ม subplot ให้กับรูปปัจจุบัน

  • วาดเส้นโดยใช้จุด x และ y2 ด้วยเมธอด plot()

  • ตั้งค่าชื่อเรื่อง ป้ายกำกับแกน X และ Y สำหรับกราฟที่ 2

  • ใช้ plt.show() เพื่อแสดงรูป

ตัวอย่าง

from matplotlib import pyplot as plt
import numpy as np
xPoints = np.array([2, 4, 6, 8, 10, 12, 14, 16, 18, 20])
y1Points = np.array([12, 14, 16, 18, 10, 12, 14, 16, 18, 120])
y2Points = np.array([12, 7, 6, 5, 4, 3, 2, 2, 1, 12])
plt.subplot(1, 2, 1) # row 1, col 2 index 1
plt.plot(xPoints, y1Points)
plt.title("My first plot!")
plt.xlabel('X-axis ')
plt.ylabel('Y-axis ')
plt.subplot(1, 2, 2) # index 2
plt.plot(xPoints, y2Points)
plt.title("My second plot!")
plt.xlabel('X-axis ')
plt.ylabel('Y-axis ')
plt.show()

ผลลัพธ์

วิธาสร้างกราฟสองกราฟวางติดกันด้วย Python