具有导航工具栏坐标的wpPython中嵌入的matplotlib

时间:2018-10-18 18:43:45

标签: python matplotlib wxpython

我碰到并用wxPython面板中嵌入的matplotlib图形实现了一些脚本。实际图的嵌入很好,但是当我添加导航工具栏NavigationToolbar2WxAgg时,许多工具栏功能都会丢失。我可以平移和缩放,但是没有显示坐标,并且默认快捷键不起作用。 matplotlib的example / user_interfaces文件夹中的embedding_in_wx4_sgskip.py中发生相同的行为:

from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.backends.backend_wx import NavigationToolbar2Wx as NavigationToolbar
from matplotlib.figure import Figure

import numpy as np
import matplotlib as mpl

import wx
import wx.lib.mixins.inspection as WIT


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

        self.figure = Figure()
        self.axes = self.figure.add_subplot(111)
        t = np.arange(0.0, 3.0, 0.01)
        s = np.sin(2 * np.pi * t)

        self.axes.fmt_xdata = lambda x: "{0:f}".format(x)
        self.axes.fmt_ydata = lambda x: "{0:f}".format(x)        

        self.axes.plot(t, s)
        self.canvas = FigureCanvas(self, -1, self.figure)

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.EXPAND)
        self.SetSizer(self.sizer)
        self.Fit()
        self.add_toolbar()  # comment this out for no toolbar

    def add_toolbar(self):
        self.toolbar = NavigationToolbar(self.canvas)
        self.toolbar.Realize()
        # By adding toolbar in sizer, we are able to put it at the bottom
        # of the frame - so appearance is closer to GTK version.
        self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND)
        # update the axes menu on the toolbar
        self.toolbar.update()


# alternatively you could use
#class App(wx.App):
class App(WIT.InspectableApp):
    def OnInit(self):
        'Create the main window and insert the custom frame'
        self.Init()
        frame = CanvasFrame()
        frame.Show(True)

        return True

app = App(0)
app.MainLoop()

如何还原此功能或将其添加到导航栏?

1 个答案:

答案 0 :(得分:0)

您可以在此处放置此代码:

    #Create 'Position Display'
    self.Text = wx.StaticText( self, wx.ID_ANY, u"  Available Channels  ", wx.DefaultPosition, wx.DefaultSize, 0 )
    self.Text.Wrap( -1 )
    mouseMoveID = self.canvas.mpl_connect('motion_notify_event',
                                                 self.onMotion)

在创建尺寸调整器之前。然后将其添加到 init 定义的末尾:

    self.sizer.Add(self.Text,0, wx.LEFT | wx.EXPAND)

最后,添加此功能以捕获鼠标在框架上的移动:

def onMotion(self, evt):
    """This is a bind event for the mouse moving on the MatPlotLib graph
        screen. It will give the x,y coordinates of the mouse pointer.
    """
    xdata = evt.xdata
    ydata = evt.ydata
    try:
        x = round(xdata,4)
        y = round(ydata,4)
    except:
        x = ""
        y = ""

    self.Text.SetLabelText("%s (s), %s" % (x,y))

这对我有用,祝你好运!