Getting PySide to work with matplotlib
The example that you mention:
http://www.scipy.org/Cookbook/Matplotlib/PySide
works, but you might need to suggest the use of PySide:
...matplotlib.use('Qt4Agg')matplotlib.rcParams['backend.qt4']='PySide'import pylab...
I had similar goals (LGPL, potential commercial use) and here's how I ended up getting it to work.
Create a matplotlib widget (see here for a more detailed one for PyQt):
import matplotlibmatplotlib.use('Qt4Agg')matplotlib.rcParams['backend.qt4']='PySide'from matplotlib.figure import Figurefrom matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvasclass MatplotlibWidget(FigureCanvas): def __init__(self, parent=None,xlabel='x',ylabel='y',title='Title'): super(MatplotlibWidget, self).__init__(Figure()) self.setParent(parent) self.figure = Figure() self.canvas = FigureCanvas(self.figure) self.axes = self.figure.add_subplot(111) self.axes.set_xlabel(xlabel) self.axes.set_ylabel(ylabel) self.axes.set_title(title)
In Qt Designer I created a blank widget to hold my plot and then when I __init__
the main window I call setupPlot:
def setupPlot(self): # create a matplotlib widget self.DataPlot = MatplotlibWidget() # create a layout inside the blank widget and add the matplotlib widget layout = QtGui.QVBoxLayout(self.ui.widget_PlotArea) layout.addWidget(self.DataPlot,1)
Then I call plotDataPoints as needed:
def plotDataPoints(self,x,y): self.DataPlot.axes.clear() self.DataPlot.axes.plot(x,y,'bo-') self.DataPlot.draw()
Note: this clears and redraws the entire plot every time (since the shape of my data keeps changing) and so isn't fast.
I think you may have posted this on the matplotlib mailing list. But just in case someone else is looking for the answer. The best option is to use the master branch on Github, but if you can't or don't know how to work the Github version you can use the following code to render a plot in PySide.
import numpy as npfrom matplotlib import useuse('AGG')from matplotlib.transforms import Bboxfrom matplotlib.path import Pathfrom matplotlib.patches import Rectanglefrom matplotlib.pylab import *from PySide import QtCore,QtGuirect = Rectangle((-1, -1), 2, 2, facecolor="#aaaaaa")gca().add_patch(rect)bbox = Bbox.from_bounds(-1, -1, 2, 2)for i in range(12): vertices = (np.random.random((4, 2)) - 0.5) * 6.0 vertices = np.ma.masked_array(vertices, [[False, False], [True, True], [False, False], [False, False]]) path = Path(vertices) if path.intersects_bbox(bbox): color = 'r' else: color = 'b' plot(vertices[:,0], vertices[:,1], color=color)app = QtGui.QApplication(sys.argv)gcf().canvas.draw()stringBuffer = gcf().canvas.buffer_rgba(0,0)l, b, w, h = gcf().bbox.boundsqImage = QtGui.QImage(stringBuffer, w, h, QtGui.QImage.Format_ARGB32)scene = QtGui.QGraphicsScene()view = QtGui.QGraphicsView(scene)pixmap = QtGui.QPixmap.fromImage(qImage)pixmapItem = QtGui.QGraphicsPixmapItem(pixmap)scene.addItem(pixmapItem)view.show()app.exec_()