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

วิธีเพิ่มกราฟเล็ก (Inset Plot) ภายในกราฟหลักใน Matplotlib Python

การเพิ่มกราฟเล็ก (Inset Axes) ภายในกราฟหลักใน Matplotlib ทำได้ด้วย fig.add_axes([left, bottom, width, height]) โดยระบุตำแหน่งและขนาดในพิกัด Figure (0-1)

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

  1. นำเข้า numpy และ matplotlib.pyplot
  2. สร้างข้อมูล X และ Y
  3. สร้าง Figure และ Axes หลักด้วย plt.subplots()
  4. สร้าง Inset Axes ด้วย fig.add_axes([left, bottom, width, height])
  5. พลอตข้อมูลบน Axes หลักและ Inset Axes แยกกัน
  6. แสดงผลด้วย plt.show()

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

import numpy as np
from matplotlib import pyplot as plt

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

x = np.linspace(-1, 1, 100)
y = np.sin(x)

fig, ax = plt.subplots()
left, bottom, width, height = [.30, 0.6, 0.2, 0.25]
ax_new = fig.add_axes([left, bottom, width, height])

ax.plot(x, y, color='red')
ax_new.plot(x, y, color='green')

plt.show()

คำอธิบายพิกัด Inset

  • left=0.30 - ระยะจากขวา Figure 30%
  • bottom=0.6 - ระยะจากล่าง Figure 60%
  • width=0.2 - ความกว้าง 20% ของ Figure
  • height=0.25 - ความสูง 25% ของ Figure
  • ค่าทั้งหมดในช่วง 0-1 (relative to figure)

ทางเลือกที่ดีกว่า: ใช้ inset_axes()


from mpl_toolkits.axes_grid1.inset_locator import inset_axes

# สร้าง inset axes ขนาด 30% ของ axes หลัก ตำแหน่งมุมขวาบน
ax_inset = inset_axes(ax, width="30%", height="30%", loc='upper right')
ax_inset.plot(x, y, 'g-')

# หรือระบุตำแหน่งแน่นอน
ax_inset = inset_axes(ax, width=2, height=1.5, loc='lower left',
                      bbox_to_anchor=(0.1, 0.1, 0.5, 0.5),
                      bbox_transform=ax.transAxes)

การเพิ่มกรอบและการเชื่อมโยง


from mpl_toolkits.axes_grid1.inset_locator import mark_inset

# วาดกรอบบน axes หลัก และเส้นเชื่อมไป inset
mark_inset(ax, ax_inset, loc1=2, loc2=4, fc="none", ec="0.5")

การประยุกต์ใช้

เหมาะสำหรับการแสดงรายละเอียดจุดที่น่าสนใจ (Zoom-in) การแสดงมุมมองต่างกันของข้อมูลเดียวกัน หรือการเปรียบเทียบสเกลต่างๆ ในกราฟเดียว