在 pyqt5 gui 中嵌入 matplotlib 图 [英] Embed a matplotlib plot in a pyqt5 gui

查看:176
本文介绍了在 pyqt5 gui 中嵌入 matplotlib 图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在与PyQt5一起尝试为我的数据分析工具生成一个GUI.我的问题是我不明白如何嵌入具有完整功能的 matplotlib 图.

I'm working with PyQt5 trying to generate a GUI for my data analysis tool. My problem is that I don't understand how to embed a matplotlib plot with full functionality.

所有关于 PyQt5 以及如何嵌入 matplotlib 的教程都展示了一种非常简单的方法,他们直接在代码中创建所有图形对象.我不想这样做,因为我的GUI是用Qt Designer生成的.我创建了一个 QWidget 来在其中绘制数据.因此,我将UI文件导入代码:

All of the tutorials about PyQt5 and how to embed matplotlib show a very simple way where they create all of the graphical object directly in the code. I don't want to do that because my GUI was generated with Qt Designer. I created a QWidget to plot data in it. Therefore, I import the UI file in the code:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import numpy as np

from PyQt5.QtGui import QPixmap
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QLabel, QGridLayout, QWidget, QTableWidget, QTableWidgetItem
from PyQt5.QtWidgets import QApplication, QWidget, QInputDialog, QLineEdit, QFileDialog
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtCore import QSize
from PyQt5 import QtCore, QtGui, uic

import matplotlib
matplotlib.use('QT5Agg')

import matplotlib.pylab as plt

from matplotlib.backends.qt_compat import QtCore, QtWidgets, is_pyqt5
from matplotlib.backends.backend_qt5agg import FigureCanvas,     NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure

class MyWindow(QMainWindow):
    def __init__(self):

        super(MyWindow, self).__init__()

        self.ui = uic.loadUi('test.ui', self) 

        # test data
        data = np.array([0.7,0.7,0.7,0.8,0.9,0.9,1.5,1.5,1.5,1.5])        
        fig, ax1 = plt.subplots()
        bins = np.arange(0.6, 1.62, 0.02)
        n1, bins1, patches1 = ax1.hist(data, bins, alpha=0.6, density=False, cumulative=False)

        # plot
        self.plotWidget = FigureCanvas(fig)        

        # add toolbar
        self.addToolBar(QtCore.Qt.BottomToolBarArea, NavigationToolbar(self.plotWidget, self))        

    #########################################

    # show window
    self.show() 

    #########################################

if __name__ == '__main__':

    app = QtWidgets.QApplication(sys.argv)
    window = MyWindow()
    sys.exit(app.exec_())

这是Qt Designer创建的test.ui文件:

This is test.ui file created by Qt Designer:

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>Form</class>
 <widget class="QWidget" name="Form">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>772</width>
    <height>650</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Form</string>
  </property>
  <widget class="QWidget" name="plotWidge" native="true">
   <property name="geometry">
    <rect>
     <x>20</x>
     <y>20</y>
     <width>721</width>
     <height>571</height>
    </rect>
   </property>
  </widget>
 </widget>
 <resources/>
 <connections/>
</ui>

发生的事情是,我可以在窗口中看到一个工具栏,但现在可以看到数据.我可以使用保存"图标将绘图保存为图像.我认为我正在创建一个窗口小部件对象的第二个实例,该实例与我在Qt Designer中创建的那个实例不相关.

What happened is that I can see a toolbar in my window but now data. I can use the "save" icon to save the plot as an image. I think that I'm creating a second instance of a widget object that is not correlated to the one I created in Qt Designer.

我该如何解决这个问题?提前致谢!

How can I solve this problem? Thanks in advance!

推荐答案

我认为您在Qt Designer中创建了一个名为 plotWidge 的小部件,而您正在做 self.plotWidget =FigureCanvas(fig) 正在替换它(即使名称一致,action 不是完成的那个),这样它就不会引起混淆将 plotWidge 更改为 content_plot在Qt Designer中,因此必须在布局的帮助下将 plotWidget 放置在 content_plot 中.

I think you are confusing that you have created a widget called plotWidge in Qt Designer and you doing self.plotWidget = FigureCanvas(fig) are replacing it (even if the names coincide that action is not the one done), so that it does not cause confusion change plotWidge to content_plot in Qt Designer so the plotWidget must be placed in content_plot with the help of a layout.

test.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>Form</class>
 <widget class="QWidget" name="Form">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>772</width>
    <height>650</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Form</string>
  </property>
  <widget class="QWidget" name="content_plot" native="true">
   <property name="geometry">
    <rect>
     <x>20</x>
     <y>20</y>
     <width>721</width>
     <height>571</height>
    </rect>
   </property>
  </widget>
 </widget>
 <resources/>
 <connections/>
</ui>

*.py

import sys
import numpy as np

from PyQt5 import QtCore, QtWidgets, uic

import matplotlib
matplotlib.use('QT5Agg')

import matplotlib.pylab as plt
from matplotlib.backends.backend_qt5agg import FigureCanvas 
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar

class MyWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(MyWindow, self).__init__()
        uic.loadUi('test.ui', self) 
        # test data
        data = np.array([0.7,0.7,0.7,0.8,0.9,0.9,1.5,1.5,1.5,1.5])        
        fig, ax1 = plt.subplots()
        bins = np.arange(0.6, 1.62, 0.02)
        n1, bins1, patches1 = ax1.hist(data, bins, alpha=0.6, density=False, cumulative=False)
        # plot
        self.plotWidget = FigureCanvas(fig)
        lay = QtWidgets.QVBoxLayout(self.content_plot)  
        lay.setContentsMargins(0, 0, 0, 0)      
        lay.addWidget(self.plotWidget)
        # add toolbar
        self.addToolBar(QtCore.Qt.BottomToolBarArea, NavigationToolbar(self.plotWidget, self))

if __name__ == '__main__':

    app = QtWidgets.QApplication(sys.argv)
    window = MyWindow()
    window.show()
    sys.exit(app.exec_())

这篇关于在 pyqt5 gui 中嵌入 matplotlib 图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆