matplotlib, встроенный в wxPython с координатами панели навигации

1

Я встретил и реализовал несколько сценариев с фигурами matplotlib, встроенными в панель wxPython. Вложение фактического графика прекрасное, но когда я добавляю панель навигации NavigationToolbar2WxAgg большая часть функциональности панели инструментов теряется. Я могу панорамировать и масштабировать, но координаты не отображаются, а сочетания клавиш по умолчанию не работают. Такое же поведение происходит в embedding_in_wx4_sgskip.py из папки example/user_interfaces для matplotlib:

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()

Как восстановить или добавить эту функциональность в панель навигации?

Теги:
matplotlib
wxpython

1 ответ

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))

Это то, что сработало для меня, удачи!

Ещё вопросы

Сообщество Overcoder
Наверх
Меню