让PySide使用matplotlib

2024-05-20 14:10:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我已尝试运行example code on the SciPy website,但出现以下错误:

Traceback (most recent call last):
  File ".\matplotlibPySide.py", line 24, in <module>
    win.setCentralWidget(canvas)
TypeError: 'PySide.QtGui.QMainWindow.setCentralWidget' called with wrong argument types:
  PySide.QtGui.QMainWindow.setCentralWidget(FigureCanvasQTAgg)
Supported signatures:
  PySide.QtGui.QMainWindow.setCentralWidget(PySide.QtGui.QWidget)

我正在构建一个简单的科学数据记录器,它最终将用于商业应用程序,因此我真的需要来自PySide的LGPL和绘图功能。有没有人有经验,如何使这一工作或替代绘图包或想法?

提前谢谢。


Tags: the绘图mostonexample错误codewebsite
2条回答

我有类似的目标(LGPL,潜在的商业用途),下面是我如何让它开始工作的。

创建matplotlib小部件(有关PyQt的详细信息,请参见here):

import matplotlib

matplotlib.use('Qt4Agg')
matplotlib.rcParams['backend.qt4']='PySide'

from matplotlib.figure import Figure
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas

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

在Qt设计器中,我创建了一个空白小部件来保存我的绘图,然后当我在主窗口中调用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)

然后根据需要调用plotDataPoints:

def plotDataPoints(self,x,y):        
    self.DataPlot.axes.clear()
    self.DataPlot.axes.plot(x,y,'bo-')
    self.DataPlot.draw()

注意:这会每次清除并重新绘制整个绘图(因为我的数据形状不断变化),因此速度不快。

你提到的例子:

http://www.scipy.org/Cookbook/Matplotlib/PySide

可以,但您可能需要建议使用PySide:

...
matplotlib.use('Qt4Agg')
matplotlib.rcParams['backend.qt4']='PySide'
import pylab
...

我想你可能把这个贴在matplotlib的邮件列表上了。但以防有人在寻找答案。最好的选择是使用Github上的master分支,但是如果您不能或不知道如何使用Github版本,可以使用以下代码在PySide中呈现一个绘图。

import numpy as np
from matplotlib import use
use('AGG')
from matplotlib.transforms import Bbox
from matplotlib.path import Path
from matplotlib.patches import Rectangle
from matplotlib.pylab import *
from PySide import QtCore,QtGui

rect = 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.bounds

qImage = 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_()

我想你可能把这个贴在matplotlib邮件列表上了。但以防有人在寻找答案。最好的选择是使用Github上的master分支,但是如果您不能或不知道如何使用Github版本,可以使用以下代码在PySide中呈现一个绘图。

import numpy as np
from matplotlib import use
use('AGG')
from matplotlib.transforms import Bbox
from matplotlib.path import Path
from matplotlib.patches import Rectangle
from matplotlib.pylab import *
from PySide import QtCore,QtGui

rect = 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.bounds

qImage = 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_()

相关问题 更多 >