本文目的:展示 PyQt5 结合 matplotlib 时,如何显示其 NavigationToolbar。

本人搜遍所有网络无果,没办法,查看PyQt5源代码,最终才搞明白。。。特此留记。

〇、PyQt4 与 PyQt5 导入 NavigationToolbar 时的区别(去掉两个agg)

  1. # PyQt4 版本(网传)
  2. #from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar
  3.  
  4. # PyQt5 版本
  5. from matplotlib.backends.backend_qt5 import NavigationToolbar2QT as NavigationToolbar

一、隐藏 matplotlib 工具条

  1. import sys
  2. from PyQt5 import QtWidgets
  3.  
  4. from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
  5. from matplotlib.backends.backend_qt5 import NavigationToolbar2QT as NavigationToolbar
  6. import matplotlib.pyplot as plt
  7.  
  8. import random
  9.  
  10. class Window(QtWidgets.QDialog):
  11. def __init__(self, parent=None):
  12. super().__init__(parent)
  13.  
  14. self.figure = plt.figure()
  15. self.axes = self.figure.add_subplot(111)
  16. # We want the axes cleared every time plot() is called
  17. self.axes.hold(False)
  18. self.canvas = FigureCanvas(self.figure)
  19.  
  20. self.toolbar = NavigationToolbar(self.canvas, self)
  21. self.toolbar.hide()
  22.  
  23. # Just some button
  24. self.button1 = QtWidgets.QPushButton('Plot')
  25. self.button1.clicked.connect(self.plot)
  26.  
  27. self.button2 = QtWidgets.QPushButton('Zoom')
  28. self.button2.clicked.connect(self.zoom)
  29.  
  30. self.button3 = QtWidgets.QPushButton('Pan')
  31. self.button3.clicked.connect(self.pan)
  32.  
  33. self.button4 = QtWidgets.QPushButton('Home')
  34. self.button4.clicked.connect(self.home)
  35.  
  36. # set the layout
  37. layout = QtWidgets.QVBoxLayout()
  38. layout.addWidget(self.toolbar)
  39. layout.addWidget(self.canvas)
  40.  
  41. btnlayout = QtWidgets.QHBoxLayout()
  42. btnlayout.addWidget(self.button1)
  43. btnlayout.addWidget(self.button2)
  44. btnlayout.addWidget(self.button3)
  45. btnlayout.addWidget(self.button4)
  46. qw = QtWidgets.QWidget(self)
  47. qw.setLayout(btnlayout)
  48. layout.addWidget(qw)
  49.  
  50. self.setLayout(layout)
  51.  
  52. def home(self):
  53. self.toolbar.home()
  54. def zoom(self):
  55. self.toolbar.zoom()
  56. def pan(self):
  57. self.toolbar.pan()
  58.  
  59. def plot(self):
  60. ''' plot some random stuff '''
  61. data = [random.random() for i in range(25)]
  62. self.axes.plot(data, '*-')
  63. self.canvas.draw()
  64.  
  65. if __name__ == '__main__':
  66. app = QtWidgets.QApplication(sys.argv)
  67.  
  68. main = Window()
  69. main.setWindowTitle('Simple QTpy and MatplotLib example with Zoom/Pan')
  70. main.show()
  71.  
  72. sys.exit(app.exec_())

二、显示 matplotlib 工具条

  1. import sys, os, random
  2.  
  3. from PyQt5.QtCore import *
  4. from PyQt5.QtGui import *
  5. from PyQt5.QtWidgets import *
  6.  
  7. import matplotlib
  8. matplotlib.use('Qt5Agg')
  9. from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
  10. from matplotlib.backends.backend_qt5 import NavigationToolbar2QT as NavigationToolbar
  11. from matplotlib.figure import Figure
  12.  
  13. class AppForm(QMainWindow):
  14. def __init__(self, parent=None):
  15. QMainWindow.__init__(self, parent)
  16. self.setWindowTitle('Demo: PyQt with matplotlib')
  17.  
  18. self.create_menu()
  19. self.create_main_frame()
  20. self.create_status_bar()
  21.  
  22. self.textbox.setText('1 2 3 4')
  23. self.on_draw()
  24.  
  25. def save_plot(self):
  26. file_choices = "PNG (*.png)|*.png"
  27.  
  28. path = QFileDialog.getSaveFileName(self,
  29. 'Save file', '',
  30. file_choices)
  31. if path:
  32. self.canvas.print_figure(path, dpi=self.dpi)
  33. self.statusBar().showMessage('Saved to %s' % path, 2000)
  34.  
  35. def on_about(self):
  36. msg = """ A demo of using PyQt with matplotlib:
  37.  
  38. * Use the matplotlib navigation bar
  39. * Add values to the text box and press Enter (or click "Draw")
  40. * Show or hide the grid
  41. * Drag the slider to modify the width of the bars
  42. * Save the plot to a file using the File menu
  43. * Click on a bar to receive an informative message
  44. """
  45. QMessageBox.about(self, "About the demo", msg.strip())
  46.  
  47. def on_pick(self, event):
  48. # The event received here is of the type
  49. # matplotlib.backend_bases.PickEvent
  50. #
  51. # It carries lots of information, of which we're using
  52. # only a small amount here.
  53. #
  54. box_points = event.artist.get_bbox().get_points()
  55. msg = "You've clicked on a bar with coords:\n %s" % box_points
  56.  
  57. QMessageBox.information(self, "Click!", msg)
  58.  
  59. def on_draw(self):
  60. """ Redraws the figure
  61. """
  62. #str = unicode(self.textbox.text())
  63. self.data = list(map(int, self.textbox.text().split()))
  64.  
  65. x = range(len(self.data))
  66.  
  67. # clear the axes and redraw the plot anew
  68. #
  69. self.axes.clear()
  70. self.axes.grid(self.grid_cb.isChecked())
  71.  
  72. self.axes.bar(
  73. left=x,
  74. height=self.data,
  75. width=self.slider.value() / 100.0,
  76. align='center',
  77. alpha=0.44,
  78. picker=5)
  79.  
  80. self.canvas.draw()
  81.  
  82. def create_main_frame(self):
  83. self.main_frame = QWidget()
  84.  
  85. # Create the mpl Figure and FigCanvas objects.
  86. # 5x4 inches, 100 dots-per-inch
  87. #
  88. self.dpi = 100
  89. self.fig = Figure((5.0, 4.0), dpi=self.dpi)
  90. self.canvas = FigureCanvas(self.fig)
  91. self.canvas.setParent(self.main_frame)
  92.  
  93. # Since we have only one plot, we can use add_axes
  94. # instead of add_subplot, but then the subplot
  95. # configuration tool in the navigation toolbar wouldn't
  96. # work.
  97. #
  98. self.axes = self.fig.add_subplot(111)
  99.  
  100. # Bind the 'pick' event for clicking on one of the bars
  101. #
  102. self.canvas.mpl_connect('pick_event', self.on_pick)
  103.  
  104. # Create the navigation toolbar, tied to the canvas
  105. #
  106. self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame)
  107.  
  108. # Other GUI controls
  109. #
  110. self.textbox = QLineEdit()
  111. self.textbox.setMinimumWidth(200)
  112. self.textbox.editingFinished.connect(self.on_draw)
  113.  
  114. self.draw_button = QPushButton("&Draw")
  115. self.draw_button.clicked.connect(self.on_draw)
  116.  
  117. self.grid_cb = QCheckBox("Show &Grid")
  118. self.grid_cb.setChecked(False)
  119. self.grid_cb.stateChanged.connect(self.on_draw) #int
  120.  
  121. slider_label = QLabel('Bar width (%):')
  122. self.slider = QSlider(Qt.Horizontal)
  123. self.slider.setRange(1, 100)
  124. self.slider.setValue(20)
  125. self.slider.setTracking(True)
  126. self.slider.setTickPosition(QSlider.TicksBothSides)
  127. self.slider.valueChanged.connect(self.on_draw)#int
  128.  
  129. #
  130. # Layout with box sizers
  131. #
  132. hbox = QHBoxLayout()
  133.  
  134. for w in [ self.textbox, self.draw_button, self.grid_cb,
  135. slider_label, self.slider]:
  136. hbox.addWidget(w)
  137. hbox.setAlignment(w, Qt.AlignVCenter)
  138.  
  139. vbox = QVBoxLayout()
  140. vbox.addWidget(self.mpl_toolbar)
  141. vbox.addWidget(self.canvas)
  142. vbox.addLayout(hbox)
  143.  
  144. self.main_frame.setLayout(vbox)
  145. self.setCentralWidget(self.main_frame)
  146.  
  147. def create_status_bar(self):
  148. self.status_text = QLabel("This is a demo")
  149. self.statusBar().addWidget(self.status_text, 1)
  150.  
  151. def create_menu(self):
  152. self.file_menu = self.menuBar().addMenu("&File")
  153.  
  154. load_file_action = self.create_action("&Save plot",
  155. shortcut="Ctrl+S", slot=self.save_plot,
  156. tip="Save the plot")
  157. quit_action = self.create_action("&Quit", slot=self.close,
  158. shortcut="Ctrl+Q", tip="Close the application")
  159.  
  160. self.add_actions(self.file_menu,
  161. (load_file_action, None, quit_action))
  162.  
  163. self.help_menu = self.menuBar().addMenu("&Help")
  164. about_action = self.create_action("&About",
  165. shortcut='F1', slot=self.on_about,
  166. tip='About the demo')
  167.  
  168. self.add_actions(self.help_menu, (about_action,))
  169.  
  170. def add_actions(self, target, actions):
  171. for action in actions:
  172. if action is None:
  173. target.addSeparator()
  174. else:
  175. target.addAction(action)
  176.  
  177. def create_action( self, text, slot=None, shortcut=None,
  178. icon=None, tip=None, checkable=False,
  179. signal="triggered()"):
  180. action = QAction(text, self)
  181. if icon is not None:
  182. action.setIcon(QIcon(":/%s.png" % icon))
  183. if shortcut is not None:
  184. action.setShortcut(shortcut)
  185. if tip is not None:
  186. action.setToolTip(tip)
  187. action.setStatusTip(tip)
  188. if slot is not None:
  189. action.triggered.connect(slot)
  190. if checkable:
  191. action.setCheckable(True)
  192. return action
  193.  
  194. def main():
  195. app = QApplication(sys.argv)
  196. form = AppForm()
  197. form.show()
  198. app.exec_()
  199.  
  200. if __name__ == "__main__":
  201. main()

PyQt5 结合 matplotlib 时,如何显示其 NavigationToolbar的更多相关文章

  1. 引用项目外dll时不显示注释的解决方案

    在引用项目外的dll时,显示类库中的注释可按以下步骤: 方法或变量用summary添加注释,如:         /// <summary>发送post请求         /// < ...

  2. HTML input="file" 浏览时只显示指定文件类型 xls、xlsx、csv

    html input="file" 浏览时只显示指定文件类型 xls.xlsx.csv <input id="fileSelect" type=" ...

  3. NTKO控件在阅读PDF时,显示DEMO的问题

    NTKO控件在阅读PDF时,显示DEMO的问题, 原因是加载了以前的DEMO版本的控件.解决办法是: 在命令行中执行命令: regsvr32 /u NtkoOleDocAll.DLL 卸载老版本的控件 ...

  4. Visio 2007中进行数据库建模时如何显示字段类型以及概念名称

    关于在VISIO中进行数据库建模时如何显示字段类型,以及注释的 1 如何显示字段类型:   在visio菜单上--->点击数据库--->选项--->文档    打开后选择表这项,在上 ...

  5. easyUI draggable插件使用不当,导致拖动div内部文本框无法输入;设置echarts数据为空时就显示空白,不要动画和文字

    先上一个Demo <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://ww ...

  6. windows7打印时,显示脱机,提示“服务器打印后台处理程序服务没有运行”。

    1. 问题 windows7打印时,显示脱机,提示“服务器打印后台处理程序服务没有运行”. 2. 解决方法. 将下面的文字保存为bat文件执行,其中\\192.168.40.110\Lenovo M7 ...

  7. <input type="file" />浏览时只显示指定文件类型

    <input type="file" />浏览时只显示指定文件类型 <input type="file" accept="appli ...

  8. Code First 中使用 ForeignKey指定外键时总是显示未引用

    Code First 中使用 ForeignKey指定外键时总是显示未引用 原因是:开发环境是在.NET 4.0 修改项目,改为.net 4.5

  9. 用Natvis定制C++对象在Visual Studio调试时如何显示

    博客搬到了fresky.github.io - Dawei XU,请各位看官挪步.最新的一篇是:用Natvis定制C++对象在Visual Studio调试时如何显示.

随机推荐

  1. Eclipse中的BuildPath详解【转载】

    什么是Build Path? Build Path是指定Java工程所包含的资源属性集合. 在一个成熟的Java工程中,不仅仅有自己编写的源代码,还需要引用系统运行库(JRE).第三方的功能扩展库.工 ...

  2. 让CI框架支持service层

    大家知道CodeIgniter框架式MVC分层的,通常大家把业务逻辑写到Controller中,而Model只负责和数据库打交道. 但是随着业务越来越复杂,controller越来越臃肿,举一个简单的 ...

  3. 【YY的GCD】

    设 \[f(n)=\sum_{i=1}^N\sum_{j=1}^M[(i,j)=n]\] 我们的答案显然是 \[ans=\sum_{p\in prime}f(p)\] 设 \[F(n)=\sum_{i ...

  4. CNN识别验证码1

    之前学习python的时候,想尝试用requests实现自动登陆,但是现在网站登陆都会有验证码保护,主要是为了防止暴力破解,任意用户注册.最近接触深度学习,cnn能够进行图像识别,能够进行验证码识别. ...

  5. ionic和angularjs的区别?

    a.ionic是一个用来开发混合手机应用的,开源的,免费的代码库.可以优化HTML.css和js的性能,构建高效的应用程序,而且还可以用于构建sass和angularJS的优化 b.AngularJS ...

  6. QTP基本方法3-----截屏

    1.桌面截屏 Desktop.captureBitMap  path[,bolean] path:保存路径,可选择绝对路径或相对路径 相对路径是保存在脚本保存的目录下编号最大的res目录下. bole ...

  7. saltstack安装配置(yum)

    主机规划: (主)master:192.168.25.130 (从)minion:192.168.25.131     192.168.25.132 1.yum安装: 服务端:安装master yum ...

  8. 在Windos上安装Nginx

    官网地址:http://nginx.org/en/download.html 1.下载 2.解压 3.启动 4.访问 打开cmd cd到nginx路径,使用命令关闭它 nginx.exe -s sto ...

  9. Selenium封装

    import os from selenium import webdriver from selenium.webdriver.common.by import By from selenium.w ...

  10. 404 Note Found 队-Alpha5

    目录 组员情况 组员1(组长):胡绪佩 组员2:胡青元 组员3:庄卉 组员4:家灿 组员5:凯琳 组员6:翟丹丹 组员7:何家伟 组员8:政演 组员9:黄鸿杰 组员10:刘一好 组员11:何宇恒 展示 ...