嵌入Wx4

如何在具有自定义工具栏的应用程序中使用wxagg的示例。

  1. from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
  2. from matplotlib.backends.backend_wxagg import NavigationToolbar2WxAgg as NavigationToolbar
  3. from matplotlib.backends.backend_wx import _load_bitmap
  4. from matplotlib.figure import Figure
  5. import numpy as np
  6. import wx
  7. class MyNavigationToolbar(NavigationToolbar):
  8. """
  9. Extend the default wx toolbar with your own event handlers
  10. """
  11. ON_CUSTOM = wx.NewId()
  12. def __init__(self, canvas, cankill):
  13. NavigationToolbar.__init__(self, canvas)
  14. # for simplicity I'm going to reuse a bitmap from wx, you'll
  15. # probably want to add your own.
  16. self.AddTool(self.ON_CUSTOM, 'Click me', _load_bitmap('back.png'),
  17. 'Activate custom contol')
  18. self.Bind(wx.EVT_TOOL, self._on_custom, id=self.ON_CUSTOM)
  19. def _on_custom(self, evt):
  20. # add some text to the axes in a random location in axes (0,1)
  21. # coords) with a random color
  22. # get the axes
  23. ax = self.canvas.figure.axes[0]
  24. # generate a random location can color
  25. x, y = np.random.rand(2)
  26. rgb = np.random.rand(3)
  27. # add the text and draw
  28. ax.text(x, y, 'You clicked me',
  29. transform=ax.transAxes,
  30. color=rgb)
  31. self.canvas.draw()
  32. evt.Skip()
  33. class CanvasFrame(wx.Frame):
  34. def __init__(self):
  35. wx.Frame.__init__(self, None, -1,
  36. 'CanvasFrame', size=(550, 350))
  37. self.figure = Figure(figsize=(5, 4), dpi=100)
  38. self.axes = self.figure.add_subplot(111)
  39. t = np.arange(0.0, 3.0, 0.01)
  40. s = np.sin(2 * np.pi * t)
  41. self.axes.plot(t, s)
  42. self.canvas = FigureCanvas(self, -1, self.figure)
  43. self.sizer = wx.BoxSizer(wx.VERTICAL)
  44. self.sizer.Add(self.canvas, 1, wx.TOP | wx.LEFT | wx.EXPAND)
  45. self.toolbar = MyNavigationToolbar(self.canvas, True)
  46. self.toolbar.Realize()
  47. # By adding toolbar in sizer, we are able to put it at the bottom
  48. # of the frame - so appearance is closer to GTK version.
  49. self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND)
  50. # update the axes menu on the toolbar
  51. self.toolbar.update()
  52. self.SetSizer(self.sizer)
  53. self.Fit()
  54. class App(wx.App):
  55. def OnInit(self):
  56. 'Create the main window and insert the custom frame'
  57. frame = CanvasFrame()
  58. frame.Show(True)
  59. return True
  60. app = App(0)
  61. app.MainLoop()

下载这个示例