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

การแสดง Scale X และ Y ต่างกันใน Zoomed Inset ด้วย Matplotlib

การสร้าง Inset Axes ที่มี Scale ต่างจากกราฟหลัก

ใช้ inset_axes() จาก mpl_toolkits.axes_grid1.inset_locator

ขั้นตอนหลัก

  • ตั้งค่าขนาดรูปและ padding
  • สร้างข้อมูล x และ y ด้วย numpy
  • เพิ่ม subplot หลักและพล็อตข้อมูล
  • สร้าง inset axes ด้วย inset_axes() กำหนด width, height, location
  • ตั้งค่า xlim, ylim ของ inset ให้ต่างจากกราฟหลัก
  • ใช้ mark_inset() วาดกล่องเชื่อมระหว่างกราฟหลักและ inset
  • แสดงผลด้วย show()

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

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.axes_grid1.inset_locator import mark_inset, inset_axes

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

x = np.linspace(0, 1, 100)
y = x ** 2

ax = plt.subplot(1, 1, 1)
ax.plot(x, y)

axins = inset_axes(ax, 1, 1, loc=2, bbox_to_anchor=(0.2, 0.55),
                   bbox_transform=ax.figure.transFigure)
axins.plot(x, y)

x1, x2 = .4, .6
y1, y2 = x1 ** 2, x2 ** 2
axins.set_xlim(x1, x2)
axins.set_ylim(y1, y2)

mark_inset(ax, axins, loc1=1, loc2=3, fc="none", ec="0.5")
plt.show()

คำอธิบาย

inset_axes() สร้าง axes ย่อยภายใน figure mark_inset() วาดเส้นเชื่อมและกล่องระบุบริเวณที่ zoom