WXにカーソルを追加する

MatplotlibMatplotlibBeginner
今すぐ練習

This tutorial is from open-source community. Access the source code

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

このチュートリアルでは、WXにカーソルを追加してデータ座標を報告するプロセスを案内します。Python用のグラフ描画ライブラリであるMatplotlibを使用します。これは、さまざまなプロット、チャート、グラフを作成するためのツールを提供します。

VMのヒント

VMの起動が完了したら、左上隅をクリックしてノートブックタブに切り替え、Jupyter Notebookを使って練習しましょう。

時々、Jupyter Notebookが読み込み終了するまで数秒待つ必要がある場合があります。Jupyter Notebookの制限により、操作の検証を自動化することはできません。

学習中に問題に遭遇した場合は、Labbyにお問い合わせください。セッション後にフィードバックを提供してください。そうすれば、迅速に問題を解決します。

キャンバスフレームを作成する

まず、Matplotlibのプロットを表示するキャンバスフレームを作成します。カーソル機能を示すために正弦波プロットを追加します。

class CanvasFrame(wx.Frame):
    def __init__(self, ):
        super().__init__(None, -1, 'CanvasFrame', size=(550, 350))

        ## Create a Figure and add a subplot
        self.figure = Figure()
        self.axes = self.figure.add_subplot()
        t = np.arange(0.0, 3.0, 0.01)
        s = np.sin(2*np.pi*t)

        ## Plot the sinusoidal curve
        self.axes.plot(t, s)
        self.axes.set_xlabel('t')
        self.axes.set_ylabel('sin(t)')

        ## Create a FigureCanvas to display the plot
        self.figure_canvas = FigureCanvas(self, -1, self.figure)

        ## Bind the motion_notify_event to update the status bar
        self.figure_canvas.mpl_connect(
          'motion_notify_event', self.UpdateStatusBar)

        ## Bind the enter_window event to change the cursor
        self.figure_canvas.Bind(wx.EVT_ENTER_WINDOW, self.ChangeCursor)

        ## Create a sizer and add the FigureCanvas to it
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.figure_canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        self.SetSizer(self.sizer)
        self.Fit()

        ## Create a status bar to report the cursor location
        self.statusBar = wx.StatusBar(self, -1)
        self.SetStatusBar(self.statusBar)

        ## Create a toolbar to navigate the plot
        self.toolbar = NavigationToolbar2Wx(self.figure_canvas)
        self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND)
        self.toolbar.Show()

カーソルを変更する

次に、キャンバスフレームにカーソルが入ったときにカーソルを変更するメソッドを定義します。この場合、カーソルをターゲットマークに変更します。

def ChangeCursor(self, event):
    self.figure_canvas.SetCursor(wx.Cursor(wx.CURSOR_BULLSEYE))

ステータスバーを更新する

最後に、マウスがプロット上を移動するたびに、カーソルの位置でステータスバーを更新するメソッドを定義します。

def UpdateStatusBar(self, event):
    if event.inaxes:
        self.statusBar.SetStatusText(f"x={event.xdata}  y={event.ydata}")

まとめ

おめでとうございます!Matplotlibを使ってWXにカーソルを追加し、データ座標を報告することに成功しました。このチュートリアルで示した手順に従えば、カーソルを自分のニーズに合わせて簡単にカスタマイズできます。