Sars30323
Sars30323

Reputation: 13

how to add the matplotlib 3d pyplot in python qt designer or pyqt5

My question is very simple but I can't find the answer, can everyone help me?

please

the question is in python GUI pyqt5, I want to draw the 3d axes using matplotlib, I find the function matplotlib.pyplot, and mpl_toolkits.mplot3d can do it well, but pyqt5 only can use the function matplotlib.figure with matplotlib.backends.backend_qt5agg.

then:

in my concept, matplotlib.backends.backend_qt5agg only draw with 2d axes, and it can't rotate.

how can I put the 3d pyplot axes on pyqt5?

my example is:

import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas

def spRDM_frame(self):
    fig = Figure()

    # note spRDM_Widget is the widget object on qt designer.
    self.ui.spRDM_Widget.canvas = FigureCanvas(fig)
    self.ui.spRDM_Widget.canvas.axes = self.ui.spRDM_Widget.canvas.figure.add_subplot(1,1,1, projection='3d')
    
    X = np.arange(-5, 5, 0.25)
    Y = np.arange(-5, 5, 0.25)
    X, Y = np.meshgrid(X, Y)
    R = np.sqrt(X ** 2 + Y ** 2)
    Z = np.sin(R)

    self.ui.spRDM_Widget.canvas.axes.plot(X,Y,Z)
    self.ui.spRDM_Widget.canvas.draw()

in the sample, not what I want.

how can I change the pyplot and setting on pyqt5.

Thanks all very much.

Upvotes: 1

Views: 3112

Answers (1)

Heike
Heike

Reputation: 24420

It is possible to draw 3D axes on a FigureCanvasQTAgg canvas using a Figure container. One issue with your code is that axes3d.plot expects 1D arrays for the x, y, and z-coordinates as input parameters but you are providing 2D arrays. To get this code to work, you need to use something like axes3d.plot_surface or axes3D.plot_wireframe instead, e.g.

from PyQt5 import QtWidgets
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
import numpy as np

class Widget(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        self.fig = Figure()
        self.canvas = FigureCanvas(self.fig)
        self.axes = self.fig.add_subplot(111, projection='3d')

        layout = QtWidgets.QVBoxLayout(self)
        layout.addWidget(self.canvas)

        X = np.arange(-5, 5, 0.25)
        Y = np.arange(-5, 5, 0.25)
        X, Y = np.meshgrid(X, Y)
        R = np.sqrt(X ** 2 + Y ** 2)
        Z = np.sin(R)

        self.axes.plot_surface(X, Y, Z)


if __name__ == "__main__":
    app = QtWidgets.QApplication([])
    win = Widget()
    win.show()
    app.exec()

Upvotes: 2

Related Questions