python通过matplotlib在坐标系中画一个矩形

2022-03-11 00:00:00 矩形 画一 坐标系

matplotlib中在坐标系中画一个蓝色背景的矩形图形。

"""
皮蛋编程(https://www.pidancode.com)
创建日期:2022/4/2
功能描述:matplotlib中,如何在坐标系中画一个矩形
"""
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle


class Annotate(object):
    def __init__(self):
        self.ax = plt.gca()
        self.rect = Rectangle((0, 0), 1, 1)
        self.x0 = None
        self.y0 = None
        self.x1 = None
        self.y1 = None
        self.ax.add_patch(self.rect)
        self.ax.figure.canvas.mpl_connect('button_press_event', self.on_press)
        self.ax.figure.canvas.mpl_connect('button_release_event', self.on_release)

    def on_press(self, event):
        print('press')
        self.x0 = event.xdata
        self.y0 = event.ydata

    def on_release(self, event):
        print('release')
        self.x1 = event.xdata
        self.y1 = event.ydata
        self.rect.set_width(self.x1 - self.x0)
        self.rect.set_height(self.y1 - self.y0)
        self.rect.set_xy((self.x0, self.y0))
        self.ax.figure.canvas.draw()


a = Annotate()
plt.show()

相关文章