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

วิธีเพิ่ม Cursor บนเส้นโค้งใน Matplotlib

ในการเพิ่ม cursor บนเส้นโค้งใน Matplotlib เราสามารถทำตามขั้นตอนต่อไปนี้:

  • ตั้งค่าขนาดรูปและปรับ padding ระหว่างและรอบ subplots
  • สร้างจุดข้อมูล t และ s ด้วย numpy
  • สร้าง figure และชุด subplots
  • รับอินสแตนซ์คลาส cursor เพื่ออัปเดตจุด cursor บน plot
  • ใน mouse_event รับข้อมูล x และ y ของตำแหน่งเมาส์ปัจจุบัน
    • รับดัชนีของจุดข้อมูล x และ y
    • ตั้งค่าตำแหน่ง x และ y
    • ตั้งค่าตำแหน่งข้อความ และ redraw agg buffer และ mouse event
  • พลอต t และ s ด้วยเมธอด plot()
  • ตั้งค่าคุณสมบัติแกนบางอย่าง
  • เพื่อแสดงรูป ใช้เมธอด show()

ตัวอย่าง

import matplotlib.pyplot as plt
import numpy as np

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

class CursorClass(object):
    def __init__(self, ax, x, y):
        self.ax = ax
        self.ly = ax.axvline(color='yellow', alpha=0.5)
        self.marker, = ax.plot([0], [0], marker="o", color="red", zorder=3)
        self.x = x
        self.y = y
        self.txt = ax.text(0.7, 0.9, '')

    def mouse_event(self, event):
        if event.inaxes:
            x, y = event.xdata, event.ydata
            indx = np.searchsorted(self.x, [x])[0]
            x = self.x[indx]
            y = self.y[indx]
            self.ly.set_xdata(x)
            self.marker.set_data([x], [y])
            self.txt.set_text('x=%1.2f, y=%1.2f' % (x, y))
            self.txt.set_position((x, y))
            self.ax.figure.canvas.draw_idle()
        else:
            return

t = np.arange(0.0, 1.0, 0.01)
s = np.sin(2 * 2 * np.pi * t)

fig, ax = plt.subplots()
cursor = CursorClass(ax, t, s)
cid = plt.connect('motion_notify_event', cursor.mouse_event)
ax.plot(t, s, lw=2, color='green')
plt.axis([0, 1, -1, 1])
plt.show()

ผลลัพธ์

วิธีเพิ่ม Cursor บนเส้นโค้งใน Matplotlibวิธีเพิ่ม Cursor บนเส้นโค้งใน Matplotlib