Home > Blockchain >  How to embed matplotlib plot PyQt5 QGroupBox
How to embed matplotlib plot PyQt5 QGroupBox

Time:05-21

I need to embed a plot into the PyQt widget. I can open the txt file with QFileDialog and plot the data separately, but I need to embed the figure into the initial solution group box. Here is the UI image. Main Window

And here is my main code.

import sys
import os
import matplotlib.pyplot as plt
import pandas as pd
from PyQt5.uic import loadUi
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QFileDialog, QDialog, QApplication, QWidget, QMainWindow, QAction
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure


class MainScreen(QMainWindow):
    def __init__(self):
        super(MainScreen, self).__init__()
        loadUi("ilk_deneme.ui", self)
        self.MenuBar()
        

    def MenuBar(self):
        Open_Data = self.actionOpen_Data
        Open_Data.triggered.connect(self.open_sheet)
        

    def open_sheet(self):
        path = QFileDialog.getOpenFileName(self, "Open", "", "TXT Files (*.txt)")
        if path[0]!='':
            self.FileN=path[0]
        self.dta_list = pd.read_csv(self.FileN,sep=",",header=None,names=["1","2"])  
        df = self.dta_list
        ax = df.plot.scatter(x="1",y="2",c="black")
        for k, v in df.iterrows():
            ax.annotate(k, v)
        plt.show()


        


app = QApplication(sys.argv)
MainScreen = MainScreen()
widget = QtWidgets.QStackedWidget()
widget.addWidget(MainScreen)
widget.setFixedHeight(656)
widget.setFixedWidth(1097)
widget.show()
try:
    sys.exit(app.exec())
except:
    print("Exiting")

CodePudding user response:

You need to create a FigureCanvas from the axis figure, then add that to the layout.

The following assumes that the "Initial Solution" group box is called initialSolution. Since you didn't provide the UI, I don't know if that box already has a layout or not, so I check for it and eventually create one.

from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar

# ...

    def open_sheet(self):
        # ...
        ax = df.plot.scatter(x="1",y="2",c="black")
        for k, v in df.iterrows():
            ax.annotate(k, v)

        layout = self.initialSolution.layout()
        if layout is None:
            layout = QVBoxLayout(self.initialSolution)

        canvas = FigureCanvas(ax.figure)
        toolbar = NavigationToolbar(canvas, self)
        layout.addWidget(toolbar)
        layout.addWidget(canvas)

Note: you're probably basing your UI on a youtube tutorial that is known to provide a lot of terrible suggestions, like adding QMainWindow (or worse, QDialog) to a QStackedWidget or that try/except block that doesn't consider nor show the exception type; I strongly discourage you to follow anything from that tutorial, and look for other sources instead. Also, MenuBar() has a name that is dangerously similar to the QMainWindow menuBar() function (and it also has a capitalized name, which is discouraged for functions); always use more descriptive names for variables and functions.

  • Related