Guest User

Untitled

a guest
Mar 19th, 2018
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.62 KB | None | 0 0
  1. # By Pierre Haessig, https://gist.github.com/pierre-haessig/9838326
  2. from pyface.qt import QtGui, QtCore
  3.  
  4. import matplotlib
  5. # We want matplotlib to use a QT backend
  6. matplotlib.use('Qt4Agg')
  7. from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
  8. from matplotlib.figure import Figure
  9.  
  10. from traits.api import Any, Instance
  11. from traitsui.qt4.editor import Editor
  12. from traitsui.qt4.basic_editor_factory import BasicEditorFactory
  13.  
  14. class _MPLFigureEditor(Editor):
  15.  
  16. scrollable = True
  17.  
  18. def init(self, parent):
  19. self.control = self._create_canvas(parent)
  20. self.set_tooltip()
  21.  
  22. def update_editor(self):
  23. pass
  24.  
  25. def _create_canvas(self, parent):
  26. """ Create the MPL canvas. """
  27. # matplotlib commands to create a canvas
  28. mpl_canvas = FigureCanvas(self.value)
  29. return mpl_canvas
  30.  
  31. class MPLFigureEditor(BasicEditorFactory):
  32.  
  33. klass = _MPLFigureEditor
  34.  
  35.  
  36. if __name__ == "__main__":
  37. # Create a window to demo the editor
  38. from traits.api import HasTraits, Int, Float, on_trait_change
  39. from traitsui.api import View, Item
  40. from numpy import sin, cos, linspace, pi
  41.  
  42. class Test(HasTraits):
  43.  
  44. figure = Instance(Figure, ())
  45. n = Int(11)
  46. a = Float(0.5)
  47.  
  48. view = View(Item('figure', editor=MPLFigureEditor(), show_label=False),
  49. Item('n'),
  50. Item('a'),
  51. width=400,
  52. height=300,
  53. resizable=True)
  54.  
  55. def __init__(self):
  56. super(Test, self).__init__()
  57. axes = self.figure.add_subplot(111)
  58. self._t = linspace(0, 2*pi, 200)
  59. self.plot()
  60.  
  61. @on_trait_change('n,a')
  62. def plot(self):
  63. t = self._t
  64. a = self.a
  65. n = self.n
  66. axes = self.figure.axes[0]
  67. if not axes.lines:
  68. axes.plot(sin(t)*(1+a*cos(n*t)), cos(t)*(1+a*cos(n*t)))
  69. else:
  70. l = axes.lines[0]
  71. l.set_xdata(sin(t)*(1+a*cos(n*t)))
  72. l.set_ydata(cos(t)*(1+a*cos(n*t)))
  73. canvas = self.figure.canvas
  74. if canvas is not None:
  75. canvas.draw()
  76.  
  77. ##############
  78. # This works #
  79. ##############
  80. t = Test()
  81. t.configure_traits()
  82.  
  83. class Container(HasTraits):
  84. p1 = Instance(Test)
  85. p2 = Instance(Test)
  86.  
  87. view = View(
  88. Item("p1", editor=MPLFigureEditor()),
  89. Item("p2", editor=MPLFigureEditor())
  90. )
  91.  
  92. ##############
  93. # This fails #
  94. ##############
  95. c = Container(p1=Test(), p2=Test())
  96. c.configure_traits()
Add Comment
Please, Sign In to add comment