PyQt5 结合 matplotlib 时,如何显示其 NavigationToolbar
本文目的:展示 PyQt5 结合 matplotlib 时,如何显示其 NavigationToolbar。
本人搜遍所有网络无果,没办法,查看PyQt5源代码,最终才搞明白。。。特此留记。
〇、PyQt4 与 PyQt5 导入 NavigationToolbar 时的区别(去掉两个agg)
# PyQt4 版本(网传)
#from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar # PyQt5 版本
from matplotlib.backends.backend_qt5 import NavigationToolbar2QT as NavigationToolbar
一、隐藏 matplotlib 工具条

import sys
from PyQt5 import QtWidgets from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5 import NavigationToolbar2QT as NavigationToolbar
import matplotlib.pyplot as plt import random class Window(QtWidgets.QDialog):
def __init__(self, parent=None):
super().__init__(parent) self.figure = plt.figure()
self.axes = self.figure.add_subplot(111)
# We want the axes cleared every time plot() is called
self.axes.hold(False)
self.canvas = FigureCanvas(self.figure) self.toolbar = NavigationToolbar(self.canvas, self)
self.toolbar.hide() # Just some button
self.button1 = QtWidgets.QPushButton('Plot')
self.button1.clicked.connect(self.plot) self.button2 = QtWidgets.QPushButton('Zoom')
self.button2.clicked.connect(self.zoom) self.button3 = QtWidgets.QPushButton('Pan')
self.button3.clicked.connect(self.pan) self.button4 = QtWidgets.QPushButton('Home')
self.button4.clicked.connect(self.home) # set the layout
layout = QtWidgets.QVBoxLayout()
layout.addWidget(self.toolbar)
layout.addWidget(self.canvas) btnlayout = QtWidgets.QHBoxLayout()
btnlayout.addWidget(self.button1)
btnlayout.addWidget(self.button2)
btnlayout.addWidget(self.button3)
btnlayout.addWidget(self.button4)
qw = QtWidgets.QWidget(self)
qw.setLayout(btnlayout)
layout.addWidget(qw) self.setLayout(layout) def home(self):
self.toolbar.home()
def zoom(self):
self.toolbar.zoom()
def pan(self):
self.toolbar.pan() def plot(self):
''' plot some random stuff '''
data = [random.random() for i in range(25)]
self.axes.plot(data, '*-')
self.canvas.draw() if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv) main = Window()
main.setWindowTitle('Simple QTpy and MatplotLib example with Zoom/Pan')
main.show() sys.exit(app.exec_())
二、显示 matplotlib 工具条

import sys, os, random from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import * import matplotlib
matplotlib.use('Qt5Agg')
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5 import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure class AppForm(QMainWindow):
def __init__(self, parent=None):
QMainWindow.__init__(self, parent)
self.setWindowTitle('Demo: PyQt with matplotlib') self.create_menu()
self.create_main_frame()
self.create_status_bar() self.textbox.setText('1 2 3 4')
self.on_draw() def save_plot(self):
file_choices = "PNG (*.png)|*.png" path = QFileDialog.getSaveFileName(self,
'Save file', '',
file_choices)
if path:
self.canvas.print_figure(path, dpi=self.dpi)
self.statusBar().showMessage('Saved to %s' % path, 2000) def on_about(self):
msg = """ A demo of using PyQt with matplotlib: * Use the matplotlib navigation bar
* Add values to the text box and press Enter (or click "Draw")
* Show or hide the grid
* Drag the slider to modify the width of the bars
* Save the plot to a file using the File menu
* Click on a bar to receive an informative message
"""
QMessageBox.about(self, "About the demo", msg.strip()) def on_pick(self, event):
# The event received here is of the type
# matplotlib.backend_bases.PickEvent
#
# It carries lots of information, of which we're using
# only a small amount here.
#
box_points = event.artist.get_bbox().get_points()
msg = "You've clicked on a bar with coords:\n %s" % box_points QMessageBox.information(self, "Click!", msg) def on_draw(self):
""" Redraws the figure
"""
#str = unicode(self.textbox.text())
self.data = list(map(int, self.textbox.text().split())) x = range(len(self.data)) # clear the axes and redraw the plot anew
#
self.axes.clear()
self.axes.grid(self.grid_cb.isChecked()) self.axes.bar(
left=x,
height=self.data,
width=self.slider.value() / 100.0,
align='center',
alpha=0.44,
picker=5) self.canvas.draw() def create_main_frame(self):
self.main_frame = QWidget() # Create the mpl Figure and FigCanvas objects.
# 5x4 inches, 100 dots-per-inch
#
self.dpi = 100
self.fig = Figure((5.0, 4.0), dpi=self.dpi)
self.canvas = FigureCanvas(self.fig)
self.canvas.setParent(self.main_frame) # Since we have only one plot, we can use add_axes
# instead of add_subplot, but then the subplot
# configuration tool in the navigation toolbar wouldn't
# work.
#
self.axes = self.fig.add_subplot(111) # Bind the 'pick' event for clicking on one of the bars
#
self.canvas.mpl_connect('pick_event', self.on_pick) # Create the navigation toolbar, tied to the canvas
#
self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame) # Other GUI controls
#
self.textbox = QLineEdit()
self.textbox.setMinimumWidth(200)
self.textbox.editingFinished.connect(self.on_draw) self.draw_button = QPushButton("&Draw")
self.draw_button.clicked.connect(self.on_draw) self.grid_cb = QCheckBox("Show &Grid")
self.grid_cb.setChecked(False)
self.grid_cb.stateChanged.connect(self.on_draw) #int slider_label = QLabel('Bar width (%):')
self.slider = QSlider(Qt.Horizontal)
self.slider.setRange(1, 100)
self.slider.setValue(20)
self.slider.setTracking(True)
self.slider.setTickPosition(QSlider.TicksBothSides)
self.slider.valueChanged.connect(self.on_draw)#int #
# Layout with box sizers
#
hbox = QHBoxLayout() for w in [ self.textbox, self.draw_button, self.grid_cb,
slider_label, self.slider]:
hbox.addWidget(w)
hbox.setAlignment(w, Qt.AlignVCenter) vbox = QVBoxLayout()
vbox.addWidget(self.mpl_toolbar)
vbox.addWidget(self.canvas)
vbox.addLayout(hbox) self.main_frame.setLayout(vbox)
self.setCentralWidget(self.main_frame) def create_status_bar(self):
self.status_text = QLabel("This is a demo")
self.statusBar().addWidget(self.status_text, 1) def create_menu(self):
self.file_menu = self.menuBar().addMenu("&File") load_file_action = self.create_action("&Save plot",
shortcut="Ctrl+S", slot=self.save_plot,
tip="Save the plot")
quit_action = self.create_action("&Quit", slot=self.close,
shortcut="Ctrl+Q", tip="Close the application") self.add_actions(self.file_menu,
(load_file_action, None, quit_action)) self.help_menu = self.menuBar().addMenu("&Help")
about_action = self.create_action("&About",
shortcut='F1', slot=self.on_about,
tip='About the demo') self.add_actions(self.help_menu, (about_action,)) def add_actions(self, target, actions):
for action in actions:
if action is None:
target.addSeparator()
else:
target.addAction(action) def create_action( self, text, slot=None, shortcut=None,
icon=None, tip=None, checkable=False,
signal="triggered()"):
action = QAction(text, self)
if icon is not None:
action.setIcon(QIcon(":/%s.png" % icon))
if shortcut is not None:
action.setShortcut(shortcut)
if tip is not None:
action.setToolTip(tip)
action.setStatusTip(tip)
if slot is not None:
action.triggered.connect(slot)
if checkable:
action.setCheckable(True)
return action def main():
app = QApplication(sys.argv)
form = AppForm()
form.show()
app.exec_() if __name__ == "__main__":
main()
PyQt5 结合 matplotlib 时,如何显示其 NavigationToolbar的更多相关文章
- 引用项目外dll时不显示注释的解决方案
在引用项目外的dll时,显示类库中的注释可按以下步骤: 方法或变量用summary添加注释,如: /// <summary>发送post请求 /// < ...
- HTML input="file" 浏览时只显示指定文件类型 xls、xlsx、csv
html input="file" 浏览时只显示指定文件类型 xls.xlsx.csv <input id="fileSelect" type=" ...
- NTKO控件在阅读PDF时,显示DEMO的问题
NTKO控件在阅读PDF时,显示DEMO的问题, 原因是加载了以前的DEMO版本的控件.解决办法是: 在命令行中执行命令: regsvr32 /u NtkoOleDocAll.DLL 卸载老版本的控件 ...
- Visio 2007中进行数据库建模时如何显示字段类型以及概念名称
关于在VISIO中进行数据库建模时如何显示字段类型,以及注释的 1 如何显示字段类型: 在visio菜单上--->点击数据库--->选项--->文档 打开后选择表这项,在上 ...
- easyUI draggable插件使用不当,导致拖动div内部文本框无法输入;设置echarts数据为空时就显示空白,不要动画和文字
先上一个Demo <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://ww ...
- windows7打印时,显示脱机,提示“服务器打印后台处理程序服务没有运行”。
1. 问题 windows7打印时,显示脱机,提示“服务器打印后台处理程序服务没有运行”. 2. 解决方法. 将下面的文字保存为bat文件执行,其中\\192.168.40.110\Lenovo M7 ...
- <input type="file" />浏览时只显示指定文件类型
<input type="file" />浏览时只显示指定文件类型 <input type="file" accept="appli ...
- Code First 中使用 ForeignKey指定外键时总是显示未引用
Code First 中使用 ForeignKey指定外键时总是显示未引用 原因是:开发环境是在.NET 4.0 修改项目,改为.net 4.5
- 用Natvis定制C++对象在Visual Studio调试时如何显示
博客搬到了fresky.github.io - Dawei XU,请各位看官挪步.最新的一篇是:用Natvis定制C++对象在Visual Studio调试时如何显示.
随机推荐
- 利用TLE数据确定卫星轨道(1)-卫星轨道和TLE
1.卫星轨道 太空中卫星和天体在各种引力的作用下都在一定的轨道中周期转动着,但实际的轨道是很复杂的,一般的项目也达不到那么精确的需求(其实精确的卫星参数数据也不可能随便公开的),所以采用一阶近似的开普 ...
- 随手练——HDU 1251 统计难题
知识点:前缀树.典型的前缀树模板. 这是用next[26]数组的版本,超内存了.(后来发现,用C++交不会超,G++就会超) #include <iostream> #include &l ...
- MyBatis(1)-简单入门
简介 什么是 MyBatis ? MyBatis 是一款优秀的持久层框架,它支持定制化 SQL.存储过程以及高级映射.MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集.My ...
- canvas二三事之签名板与视频绘制
今天,不知道怎么的就点开了语雀,然后就看到了<HTML5 Canvas 教程>,开始了canvas的研究(学习)之旅. 首先,想到的第一个东西就是签名板,上代码: <canvas i ...
- 利用maven开发springMVC项目(三)——数据库配置
前两节介绍了开发环境的搭建以及框架的配置 现在主要介绍在eclipse中如何将SpringMVC.hibernate.mysql数据库结合起来. 数据库配置 下面,就要通过一个简单的例子,来介绍Spr ...
- Luogu_4197 Peaks
P4197 Peaks 并不会克鲁斯卡尔重构树,于是就写了离线算法. 使用了最小生成树,启发式合并treap 在最小生成树,克鲁斯卡尔算法 时 ,将询问一块处理.便可以保证询问时边的要求.然后利用平衡 ...
- shell习题第8题:监控nginx的502状态
[题目要求] 服务器上跑的是LNMP环境,近期总是有502现象.502为网站访问的状态码,200正常,502错误是nginx最为普遍的错误状态码. 由于502只是暂时的,并且只要一重启php-fpm服 ...
- windows 使用npm安装webpack 4.0以及配置问题的解决办法
输入cmd点击打开 输入node -v 出现nodejs版本号 输入npm -v 出现npm版本号则安装npm安装成功, 2.安装webpack 桌面新建一个webpack-test文件夹,点击进入文 ...
- Redis笔记 -- make编译安装报错记录2则(一)
1.Redis的获取与安装,目前最新稳定版本为4.0.10 Redis: https://redis.io/download GitHub: https://github.com/antirez/ ...
- phporjquery生成二维码
一.php生成二维码 下载文章末尾链接中phpcode文件 include "./phpqrcode/qrlib.php"; //QRcode::png('http://www.b ...