PyQt5嵌入3D散点图

时间:2019-12-26 21:50:30

标签: python matplotlib pyqt5

我试图在PyQt5中使用3D图,但无法使图旋转。 我已经使matplotlib工具栏工作了一半,它可以保存并调整图的大小。 缩放和移动虽然适用于2d图,但无法工作,不确定散点图是否允许缩放或移动。我需要的是轮换方式。

到目前为止的代码:

import sys
from PyQt5.QtWidgets import QWidget, QMainWindow, QApplication, QSizePolicy, QVBoxLayout, QPushButton
import matplotlib
matplotlib.use("Qt5Agg")

from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure

from mpl_toolkits.mplot3d import axes3d, Axes3D



class MyMplCanvas(FigureCanvas):
    # Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.).
    def __init__(self, parent=None, width=5, height=4, dpi=100):
        fig = Figure(figsize=(width, height), dpi=dpi)
        self.fig = fig
        self.axes = fig.add_subplot(111, projection='3d')
        # self.fig = plt.figure()
        # self.axes = Axes3D(self.fig)

        self.compute_initial_figure()
        FigureCanvas.__init__(self, self.fig)
        self.setParent(parent)

        FigureCanvas.setSizePolicy(self,
                                   QSizePolicy.Expanding,
                                   QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)

    def compute_initial_figure(self):
        pass


class MyStaticMplCanvas(MyMplCanvas):
    # Simple canvas with a sine plot.
    def compute_initial_figure(self):
        # t = arange(0.0, 3.0, 0.01)
        # s = sin(2 * pi * t)
        # self.axes.plot(t, s)
        xs = [1, 2]
        ys = [1, 2]
        zs = [1, 2]

        self.axes.scatter(xs, ys, zs, c='b')

        self.axes.mouse_init()


class PlotDialog(QWidget):
    def __init__(self):
        QWidget.__init__(self)

        self.plot_layout = QVBoxLayout(self)
        self.plot_canvas = MyStaticMplCanvas(self, width=5, height=4, dpi=100)

        self.navi_toolbar = NavigationToolbar(self.plot_canvas, self)
        self.plot_layout.addWidget(self.plot_canvas)  # the matplotlib canvas
        self.plot_layout.addWidget(self.navi_toolbar)


if __name__ == "__main__":
    import sys

    app = QApplication(sys.argv)
    dialog = PlotDialog()
    dialog.show()
    sys.exit(app.exec_())

1 个答案:

答案 0 :(得分:3)

在更新几何图形之后,您必须初始化鼠标,在这种情况下,您要在造成故障之前先进行操作。

# ...
FigureCanvas.setSizePolicy(self,
                           QSizePolicy.Expanding,
                           QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
self.axes.mouse_init()
# ...