Skip to main content
 首页 » 编程设计

python之seaborn 和 networkx 可以通过 matplotlib 集成到 GUI 中吗

2024年09月07日39think

使用下面的代码,我可以在用 pyqt5 设计的图形用户界面中绘制基本的 matplotlib 图(例如给它一个 xs 和 ys 的列表,它绘制点)。但是,我无法插入高级模块,例如 seaborn 或 networkx(让我们关注 seaborn),它们利用 matplotlib 的绘图功能来显示您使用这些函数生成的数据。

from PyQt5 import QtCore, QtGui, QtWidgets 
import numpy as np 
import pandas as pd 
import matplotlib.pyplot as plt 
import seaborn as sns 
 
class Ui_MainWindow(object): 
    def setupUi(self, MainWindow): 
        MainWindow.setObjectName("MainWindow") 
        MainWindow.resize(800, 600) 
        self.centralwidget = QtWidgets.QWidget(MainWindow) 
        self.centralwidget.setObjectName("centralwidget") 
        self.widget = MplWidget(self.centralwidget) 
        self.widget.setGeometry(QtCore.QRect(200, 110, 391, 311)) 
        self.widget.setObjectName("widget") 
        self.label = QtWidgets.QLabel(self.centralwidget) 
        self.label.setGeometry(QtCore.QRect(250, 40, 231, 61)) 
        self.label.setObjectName("label") 
        self.pushButton = QtWidgets.QPushButton(self.centralwidget) 
        self.pushButton.setGeometry(QtCore.QRect(50, 180, 113, 32)) 
        self.pushButton.setObjectName("pushButton") 
        MainWindow.setCentralWidget(self.centralwidget) 
        self.menubar = QtWidgets.QMenuBar(MainWindow) 
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 22)) 
        self.menubar.setObjectName("menubar") 
        MainWindow.setMenuBar(self.menubar) 
        self.statusbar = QtWidgets.QStatusBar(MainWindow) 
        self.statusbar.setObjectName("statusbar") 
        MainWindow.setStatusBar(self.statusbar) 
 
        self.retranslateUi(MainWindow) 
        QtCore.QMetaObject.connectSlotsByName(MainWindow) 
 
        self.pushButton.clicked.connect(self.Graphitdude) 
 
    def Graphitdude(self): 
        Lister3 = pd.read_csv("Betadata.csv",index_col=[0])#just a collection of labels and assorted correlation values ranging from 0 to 1 to be constructed into a heatmap. 
        plot = sns.heatmap(Lister3) # This is the problematic function, it does it, and I can display it IN LINE but not in the gui canvas?  
        plt.yticks(rotation=0) 
        self.widget.canvas.ax.plot()#if passed discreet x and y values, it graphs it, but it doesnt like to pass the seaborn figure? 
        self.widget.canvas.draw() 
 
    def retranslateUi(self, MainWindow): 
        _translate = QtCore.QCoreApplication.translate 
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow")) 
        self.label.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:24pt; font-weight:600;\">Test</span></p></body></html>")) 
        self.pushButton.setText(_translate("MainWindow", "PushButton")) 
 
from mplwidget import MplWidget 
 
if __name__ == "__main__": 
    import sys 
    app = QtWidgets.QApplication(sys.argv) 
    MainWindow = QtWidgets.QMainWindow() 
    ui = Ui_MainWindow() 
    ui.setupUi(MainWindow) 
    MainWindow.show() 
    sys.exit(app.exec_()) 

mplwidget.py如下:

from PyQt5 import QtWidgets 
from matplotlib.figure import Figure 
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as Canvas 
import matplotlib 
 
 
matplotlib.use('QT5Agg') 
 
# Matplotlib canvas class to create figure 
class MplCanvas(Canvas): 
    def __init__(self): 
        self.fig = Figure() 
        self.ax = self.fig.add_subplot(111) 
        Canvas.__init__(self, self.fig) 
        Canvas.setSizePolicy(self, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) 
        Canvas.updateGeometry(self) 
 
# Matplotlib widget 
class MplWidget(QtWidgets.QWidget): 
    def __init__(self, parent=None): 
        QtWidgets.QWidget.__init__(self, parent)   # Inherit from QWidget 
        self.canvas = MplCanvas()                  # Create canvas object 
        self.vbl = QtWidgets.QVBoxLayout()         # Set box for plotting 
        self.vbl.addWidget(self.canvas) 
        self.setLayout(self.vbl) 

我最好的想法是,这些函数正在设计它们自己的 matplotlib 图(或子图,不确定),并且这个图不能通过我尝试过的方法提供给小部件代码。

sns.heatmap(xxxx) 返回“ax”,mplwidget.py 脚本应该可以使用它,对吧?我可以将它们传递给 Canvas 以显示 seaborn 图形吗?

请您参考如下方法:

根据documentation :

seaborn.heatmap(data, vmin=None, vmax=None, cmap=None, center=None, robust=False, annot=None, fmt='.2g', annot_kws=None, linewidths=0, linecolor='white', cbar=True, cbar_kws=None, cbar_ax=None, square=False, xticklabels='auto', yticklabels='auto', mask=None, ax=None, **kwargs)

[...]

ax : matplotlib Axes, optional

Axes in which to draw the plot, otherwise use the currently-active Axes.

那么你应该将 MplCanvas 的 AxesSubplot 作为参数 ax 传递:

def Graphitdude(self): 
    Lister3 = pd.read_csv("Betadata.csv",index_col=[0]) 
    plot = sns.heatmap(Lister3, ax=self.widget.canvas.ax)  
    plt.yticks(rotation=0) 
    self.widget.canvas.draw() 

我使用过许多类似于 heatmap 的函数,并且总是提供该参数。