Monday, July 16, 2012

Chaco Plots Using PySide Qt Bindings with Widgets in a QVBoxLayout


This small example builds on the example found at:
http://caethan.wordpress.com/2011/09/05/chaco-plots-in-pyside/

This example can be extended to easily include multiple plots and the adjustment of
plot parameters using spin boxes.

#!/usr/bin/python

import sys
from numpy import *
from PySide.QtCore import *
from PySide.QtGui import *

app = QApplication(sys.argv)

from traits.etsconfig.etsconfig import ETSConfig
ETSConfig.toolkit = "qt4"
from enable.api import Window
from chaco.api import ArrayPlotData, Plot

class Viewer(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.mainWidget = QWidget(self) # dummy widget to contain layout manager
        self.plotview = Plotter(self)
        self.setCentralWidget(self.mainWidget)

        self.amplitudeLabel = QLabel("Amplitude: ")
        self.amplitudeSpinBox = QDoubleSpinBox()
        self.amplitudeSpinBox.setRange(-1000000.00, 1000000.00)
        self.amplitudeSpinBox.setValue(1.00)
 
        self.plotButton = QPushButton("Plot")
        self.plotButton.clicked.connect(self.update) 
                
        self.statusBar().showMessage('Ready to rock!')
        self.setWindowTitle('sin(x)')

        x = arange(100)
        y = zeros(100) 
        self.plotview.update_data(x, y)

        layout = QVBoxLayout(self.mainWidget)
        layout.addWidget(self.amplitudeLabel)
        layout.addWidget(self.amplitudeSpinBox)
        layout.addWidget(self.plotButton)
        layout.addWidget(self.plotview.widget)
        self.setLayout(layout)

     
    def update(self):
        print "Ok"
        print self.amplitudeSpinBox.value()
        x = arange(200)
        y = self.amplitudeSpinBox.value() * sin(x)
        self.plotview.update_data(x, y)
    

class Plotter():
    def __init__(self, parent):
        self.plotdata = ArrayPlotData(x=array([]),  y=array([]))
        self.window = self.create_plot(parent)
        self.widget = self.window.control
        

    def update_data(self, x, y):
        self.plotdata.set_data("x", x)
        self.plotdata.set_data("y", y)

    def create_plot(self, parent):
        plot = Plot(self.plotdata, padding=50, border_visible=True)
        plot.plot(("x", "y"), name="data plot", color="green")
        return Window(parent, -1, component=plot)


if __name__ == "__main__":
    plot = Viewer()
    plot.resize(600, 400)
    plot.show()
    sys.exit(app.exec_())