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

วิธีรวมสอง Matplotlib Plots ที่มีอยู่เป็นหนึ่ง Plot

ในการรวมสอง matplotlib plots ที่มีอยู่เป็นหนึ่ง plot เราสามารถทำตามขั้นตอนต่อไปนี้:

  • ตั้งค่าขนาดรูปและปรับ padding ระหว่างและรอบ subplots
  • สร้างจุดข้อมูล x, y1 และ y2 ด้วย numpy
  • พลอตจุด (x, y1) และ (x, y2) ด้วยเมธอด plot()
  • รับจุดข้อมูล xy ของแกนปัจจุบัน
  • ใช้ argsort() เพื่อคืนค่าดัชนีที่จะเรียงอาร์เรย์
  • ต่อท้ายจุดข้อมูล x และ y ของแต่ละ plot
  • พลอตจุดข้อมูล X และ Y ที่ subplot index ที่ 2
  • เพื่อแสดงรูป ใช้เมธอด show()

ตัวอย่าง

import numpy as np
import matplotlib.pyplot as plt

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

x = np.linspace(-10, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)

plt.subplot(211)
plt.plot(x, y1, color='red', lw=5)
plt.plot(x, y2, color='orange', lw=7)

X, Y = [], []
for lines in plt.gca().get_lines():
    for x, y in lines.get_xydata():
        X.append(x)
        Y.append(y)

idx = np.argsort(X)
X = np.array(X)[idx]
Y = np.array(Y)[idx]

plt.subplot(212)
plt.plot(X, Y, color='green', lw=0.75)
plt.show()

ผลลัพธ์

วิธีรวมสอง Matplotlib Plots ที่มีอยู่เป็นหนึ่ง Plotวิธีรวมสอง Matplotlib Plots ที่มีอยู่เป็นหนึ่ง Plot