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

การหาพื้นที่ระหว่างสองโค้งที่พล็อตใน Matplotlib


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

  • กำหนดขนาดรูปภาพและปรับระยะห่างระหว่างและรอบๆ subplots
  • สร้างข้อมูล x, c1 และ c2 ด้วย numpy
  • พล็อต (x, c1) และ (x, c2) ด้วย plot()
  • เติมสีพื้นที่ระหว่างสองโค้ง c1 และ c2 สีเทา hatch "|" ด้วย fill_between()
  • ใช้เมธอด show() เพื่อแสดงรูปภาพ

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

import matplotlib.pyplot as plt
import numpy as np

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

x = np.linspace(0, 1, 100)
c1 = x ** 2
c2 = x
plt.plot(x, c1)
plt.plot(x, c2)
plt.fill_between(x, c1, c2, color="grey", alpha=0.3, hatch='|')
plt.show()

ผลลัพธ์

การหาพื้นที่ระหว่างสองโค้งที่พล็อตใน Matplotlib