在PyQt4中使用matplotlib

matplotlib作为Python中著名的数据可视化工具,其官网也提供了在PyQt4中使用的源码,这里举一个应用实例,以备不时之需。

1) 利用Qt Designer创建GUI界面

Demo的GUI界面,如图1所示,其中利用QFrame作为放置matplotlib界面的容器。然后调用pyuic4.bat -o ui_maindialog.py maindialog.ui编译UI界面。

GUI设计界面

图1 GUI设计界面

2) maindialog.py程序代码

复制代码
#!/usr/bin/env python
#-*- coding: utf-8 -*-

import numpy as np
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from ui_maindialog import Ui_MainDialog
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas # matplotlib对PyQt4的支持
from matplotlib.figure import Figure

class MainDialog(QDialog, Ui_MainDialog):
    def __init__(self, parent=None):
        super(MainDialog, self).__init__(parent)
        self.setupUi(self)
        self._createFigures()
        self._createLayouts()

  # 创建matplotlib的画布
def _createFigures(self): self._fig = Figure(figsize=(8, 6), dpi=100, tight_layout=True) self._fig.set_facecolor("#F5F5F5") # 背景色 self._fig.subplots_adjust(left=0.08, top=0.92, right=0.95, bottom=0.1) # Margins self._canvas = FigureCanvas(self._fig) # 画布 self._ax = self._fig.add_subplot(111) # 增加subplot self._ax.hold(True) self._initializeFigure() def _createLayouts(self): layout = QHBoxLayout(self.frame) layout.setContentsMargins(0, 0, 0, 0) layout.addWidget(self._canvas) # Add Matplotli def _initializeFigure(self): Font = {'family': 'Tahoma', 'weight': 'bold', 'size': 10} # Abscissa self._ax.set_xlim([380, 780]) self._ax.set_xticks([380, 460, 540, 620, 700, 780]) self._ax.set_xticklabels([380, 460, 540, 620, 700, 780], fontdict=Font) self._ax.set_xlabel("Wavelength (nm)", fontdict=Font) # Ordinate self._ax.set_ylim([0.0, 1.0]) self._ax.set_yticks(np.arange(0.0, 1.1, 0.2)) self._ax.set_yticklabels(np.arange(0.0, 1.1, 0.2), fontdict=Font) self._ax.set_ylabel("Spectral Radiance (W/(m$^2$*sr*nm))", fontdict=Font) self._ax.grid(True) # Grid On def _updateFigures(self): Font = {'family': 'Tahoma', 'weight': 'bold', 'size': 10} self._ax.clear() maxY = 0.0 x = np.arange(380, 781) y = np.random.rand(401) self._ax.plot(x, y, 'r', label="Data")
     maxY = max(y)
if maxY <= 0: self._initializeFigure() else: self._fig.subplots_adjust(left=0.11, top=0.92, right=0.95, bottom=0.1) # Abscissa self._ax.set_xlim([380, 780]) self._ax.set_xticks([380, 460, 540, 620, 700, 780]) self._ax.set_xticklabels([380, 460, 540, 620, 700, 780], fontdict=Font) self._ax.set_xlabel("Wavelength (nm)", fontdict=Font) # Ordinate self._ax.set_ylim([0.0, maxY]) self._ax.set_yticks([0.0, maxY / 4.0, maxY / 2.0, maxY * 3 / 4.0, maxY]) self._ax.set_yticklabels( ["%.1e" % 0.0, "%.1e" % (maxY / 4.0), "%.1e" % (maxY / 2.0), "%.1e" % (maxY * 3.0 / 4.0), "%.1e" % maxY], fontdict=Font) self._ax.set_ylabel("Spectral Radiance (W/(m$^2$*sr*nm))", fontdict=Font) self._ax.grid(True) self._ax.legend(loc="best", fontsize="small").draggable(state=True) # Legend self._canvas.draw() @pyqtSlot() def on_plotPushButton_clicked(self): self._updateFigures()
复制代码

初始界面如图2所示:

图2 GUI初始界面

3) 点击plot按键后

界面显示见图3:

 

图3 点击Plot按键后界面