让 PySide 与 matplotlib 一起使用

发布于 2024-11-24 22:37:25 字数 615 浏览 1 评论 0原文

我尝试在 SciPy 网站上运行 示例代码,但收到此错误

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 和绘图功能。有谁有关于如何使其发挥作用或替代绘图包或想法的经验?

提前致谢。

I have tried running the example code on the SciPy website, but I get this error:

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)

I am building a simple scientific data logger that will eventually be used in commercial applications, so I really need both the LGPL from PySide and plotting functionality. Does anyone have experience on how to get this to work or alternative plotting packages or ideas?

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

自演自醉 2024-12-01 22:37:25

您提到的示例:

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

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

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

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
...
深爱成瘾 2024-12-01 22:37:25

我有类似的目标(LGPL,潜在的商业用途),这就是我最终让它发挥作用的方法。

创建 matplotlib 小部件(请参阅此处 有关 PyQt 的更详细信息):

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

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

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

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.

戏舞 2024-12-01 22:37:25

我想您可能已将其发布在 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_()

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 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_()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文