gui programming with matplotlib pic.twitter.com/kEI863X14U
— Kurene (@_kurene) May 11, 2020
何番煎じか分かりませんが、matplotlibでインタラクティブなプロットをする機会があったので、 メモ代わりにサンプルコードを作ってみました。
Event handling and picking によると、マウスやキーボード、ウィンドウ周りのイベント駆動プロッティングができるようです。
import sys import numpy as np import matplotlib.pyplot as plt # References: # https://matplotlib.org/3.1.1/api/backend_bases_api.html#matplotlib.backend_bases.MouseEvent # https://matplotlib.org/3.1.0/gallery/misc/cursor_demo_sgskip.html class App(object): def __init__(self, ax, clear=True): self.ax = ax self.x, self.y = 0.0, 0.0 self.clear = clear self.ax.grid() def draw(self): # Clear if self.clear: self.ax.clear() self.ax.grid() # Your plottings self.ax.plot(self.x, self.y, "*", color="c", markersize=12) ax.set_xlim(0, 5) ax.set_ylim(0, 5) # update self.ax.figure.canvas.draw() def on_press(self, event): if not event.inaxes: return print(f'on_press(): {event.button}, {event.xdata:1.2f}, {event.ydata:1.2f}', ) # Your events self.x, self.y = event.xdata, event.ydata self.draw() def on_key(self, event): print(f'on_key(): {event.key}, {event.xdata:1.2f}, {event.ydata:1.2f}', ) # Your events if event.key == "left": self.x -= 0.1 self.draw() elif event.key == "right": self.x += 0.1 self.draw() elif event.key == "down": self.y -= 0.1 self.draw() elif event.key == "up": self.y += 0.1 self.draw() elif event.key == "c": self.ax.clear() ax.set_xlim(0, 5) ax.set_ylim(0, 5) ax.grid() self.ax.figure.canvas.draw() clear = False if int(sys.argv[1]) == 0 else True fig, ax = plt.subplots() app = App(ax,clear=clear) fig.canvas.mpl_connect('key_press_event', app.on_key) fig.canvas.mpl_connect('button_press_event', app.on_press) plt.show()