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

วิธีพล็อตกราฟสี 2D แบบเรียบสำหรับ z = f(x, y) ใน Matplotlib


เพื่อพล็อตกราฟสี 2D แบบเรียบสำหรับ z = f(x, y) ใน Matplotlib ให้ทำตามขั้นตอน:

  • กำหนดขนาดรูปและปรับระยะห่างระหว่างและรอบซับพล็อต
  • สร้างจุดข้อมูล x และ y ด้วย NumPy
  • คำนวณจุดข้อมูล z จาก f(x, y)
  • แสดงข้อมูลเป็นภาพบน raster 2D ปกติด้วยจุดข้อมูล z
  • ใช้ show() เพื่อแสดงรูป

ตัวอย่าง

import numpy as np
from matplotlib import pyplot as plt

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

def f(x, y):
    return np.array([i * i + j * j for j in y for i in x]).reshape(5, 5)

x = y = np.linspace(-1, 1, 5)
z = f(x, y)
plt.imshow(z, interpolation='bilinear')
plt.show()

ผลลัพธ์

วิธีพล็อตกราฟสี 2D แบบเรียบสำหรับ z = f(x, y) ใน Matplotlib