使用PyQt5嵌入动态条形图

2024-02-29

我在 python 中编写了以下代码,以在生成的 GUI 中显示条形图PyQt5.

import sys
from PyQt5.QtWidgets import QDialog, QApplication, QPushButton, QVBoxLayout, \
QLineEdit, QMessageBox, QInputDialog, QLabel, QHBoxLayout, QGridLayout,     QStackedLayout, QFormLayout
from  PyQt5 import QtCore, QtGui, QtWidgets
import time
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.lines import Line2D

import matplotlib.animation as animation
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as     NavigationToolbar
import matplotlib.pyplot as plt
# data
import numpy as np
#import matplotlib.pyplot as plt
import pandas as pd
import os
import csv

#define  the path to data
pathToData='C:/RC/python/data/'
dataName= '31122017ARB.csv'
# import 
data=pd.read_csv(pathToData+dataName, delimiter=';',encoding='cp1252')


# percent  MW
data['MWP']=data[' MW ']/sum(data[' MW '])
#aggregate by   Best
datag=data.groupby('Best', as_index=False).agg({'MW': 'sum'})
x=["BE"+s for s in[str(s) for s in [int(x) for x in datag.iloc[:,0].tolist()]]]
y=datag.ix[:,1].tolist()




figure = plt.figure()

H = np.array([[100, 2, 39, 190], [402, 55, 369, 1023], [300, 700, 8, 412], [170, 530, 330, 1]])
Z = np.array([[3, 290, 600, 480], [1011, 230, 830, 0], [152, 750, 5, 919], [340, 7, 543, 812]])


class Window(QDialog):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        # a figure instance to plot on
        self.figure = plt.figure()

        # this is the Canvas Widget that displays the `figure`
        # it takes the `figure` instance as a parameter to __init_
        self.im = None
        self.canvas = FigureCanvas(self.figure)

        self.canvas.mpl_connect('button_press_event', self.on_button_press_event)

        # this is the Navigation widget
        # it takes the Canvas widget and a parent
        self.toolbar = NavigationToolbar(self.canvas, self)

        self.timer = QtCore.QTimer(self)
        self.timer.timeout.connect(self.plot)
        self.timer.setInterval(5000)

        # Just some button connected to `plot` method
        self.button = QPushButton('Plot')
        self.button.clicked.connect(self.timer.start)
        self.button.setDefault(False)

        self.stop = QPushButton("Stop")
        self.stop.clicked.connect(self.timer.stop)
        self.stop.setDefault(False)

        self.exit = QPushButton('Exit')
        self.exit.clicked.connect(self.close)
        self.exit.setDefault(True)

         layout = QFormLayout()
        layout.addWidget(self.toolbar)
        layout.addWidget(self.canvas)
        layout.addWidget(self.button)
        layout.addWidget(self.stop)
        layout.addWidget(self.exit)

        self.setLayout(layout)

        self.lb = QtWidgets.QLabel(self)
        self.lb.setWindowFlags(QtCore.Qt.ToolTip)

            def plot(self):
        self.x  = ["BE"+s for s in[str(s) for s in [int(x) for x in datag.iloc[:,0].tolist()]]]
        self.y  = datag.iloc[:,1].tolist()#np.sin(self.x)

        self.setWindowTitle("Bestandseingruppierung")

    def update_figure(self):
        self.axes.bar(self.x, self.y)
        #self.y = np.roll(self.y,-1)
        #self.draw()
        self.canvas.draw()
    def on_button_press_event(self, event):
        print('button={}, x={}, y={}, xdata={}, ydata={}'
            .format(event.button, event.x, event.y, event.xdata, event.ydata))

       if self.im:
                message = str(self.im.get_cursor_data(event))
                delay = 1000
                w = self.lb.fontMetrics().width(message)
                self.lb.resize(w, self.lb.size().height())
                self.lb.setText(message)
                self.lb.move(QtGui.QCursor.pos())
                self.lb.show()
                QtCore.QTimer.singleShot(delay, self.lb.hide)




    if __name__ == '__main__':
        app = QApplication(sys.argv)

        main = Window()
        main.show()

        sys.exit(app.exec_())

The Problem is: it is not shown any plot, even I do not get any error. I just obtain an empty window.

如何通过按绘图底部来获取图表?我想,我在下面做错了一些事情def plot(self):.

只是为了澄清:我在 PyQt5 生成的 GUI 中作为独立代码测试了图表,它工作得很好:

# FigureCanvas inherits QWidget
class MainWindow(FigureCanvas):
    def __init__(self, parent=None, width=4, height=3, dpi=100):
        fig = Figure(figsize=(width, height), dpi=dpi)
        self.axes = fig.add_subplot(111)
        self.axes.hold(False)

        super(MainWindow, self).__init__(fig)
        self.setParent(parent)

        FigureCanvas.setSizePolicy(self,
                                   QSizePolicy.Expanding,
                                   QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)

        timer = QTimer(self)
        timer.timeout.connect(self.update_figure)
        timer.start(50)

        self.x  = ["BE"+s for s in[str(s) for s in [int(x) for x in datag.iloc[:,0].tolist()]]]#np.arange(0, 4*np.pi, 0.1)
        self.y  = datag.iloc[:,1].tolist()#np.sin(self.x)

        self.setWindowTitle("Best")

    def update_figure(self):
        self.axes.bar(self.x, self.y)
        #self.y = np.roll(self.y,-1)
        self.draw()

if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    mainWindow = MainWindow()

    mainWindow.show()
sys.exit(app.exec_())

我找到了解决方案!

我在此 GUI 中有 3 个按钮,如以下代码部分所示:

class Window(QDialog):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        # a figure instance to plot on
        self.figure = plt.figure()

        # this is the Canvas Widget that displays the `figure`
        # it takes the `figure` instance as a parameter to __init_
        self.im = None
        self.canvas = FigureCanvas(self.figure)

        self.canvas.mpl_connect('button_press_event', self.on_button_press_event)

        # this is the Navigation widget
        # it takes the Canvas widget and a parent
        self.toolbar = NavigationToolbar(self.canvas, self)

        self.timer = QtCore.QTimer(self)
        self.timer.timeout.connect(self.plot)
        self.timer.setInterval(0)

        # Just some button connected to `plot` method
        self.button = QPushButton('Plot')
        self.button.clicked.connect(self.timer.start)
        self.button.setDefault(False)

        self.stop = QPushButton("Stop")
        self.stop.clicked.connect(self.timer.stop)
        self.stop.setDefault(False)

        self.exit = QPushButton('Exit')
        self.exit.clicked.connect(self.close)
        self.exit.setDefault(True)

必须将时间延迟设置为self.timer.setInterval(0)归零!这是第一点。

那个部分def plot(self)应更改如下:

def plot(self):
        data=x
        self.setWindowTitle("Bestandseingruppierung")
        # instead of ax.hold(False)
        self.figure.clear()

        # create an axis
        ax = self.figure.add_subplot(111)
        #fig.autofmt_xdate()
        # discards the old graph
        ax.hold(False) # deprecated, see above

        # plot data
        ax.axes.bar(data,y)
        self.canvas.draw()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用PyQt5嵌入动态条形图 的相关文章

  • 如何 json_normalize() df 中的特定字段并保留其他列? [复制]

    这个问题在这里已经有答案了 这是我的简单示例 我的实际数据集中的 json 字段非常嵌套 因此我一次解压一层 我需要在 json normalize 之后保留数据集上的某些列 https pandas pydata org docs ref
  • 如何用spaCy获取依赖树?

    我一直在尝试寻找如何使用 spaCy 获取依赖树 但我找不到任何有关如何获取树的信息 只能在如何导航树 https spacy io usage examples subtrees 如果有人想轻松查看 spacy 生成的依赖关系树 一种解决
  • 蟒蛇 |如何将元素随机添加到列表中

    有没有一种方法可以将元素随机添加到列表中 内置函数 ex def random append lst a lst append b lst append c lst append d lst append e return print ls
  • Pytest:如何使用从夹具返回的列表来参数化测试?

    我想使用由固定装置动态创建的列表来参数化测试 如下所示 pytest fixture def my list returning fixture depends on other fixtures return a dynamically
  • 如何在“python setup.py test”中运行 py.test 和 linter

    我有一个项目setup py文件 我用pytest作为测试框架 我还在我的代码上运行各种 linter pep8 pylint pydocstyle pyflakes ETC 我用tox在多个 Python 版本中运行它们 并使用以下命令构
  • multiprocessing.freeze_support()

    为什么多处理模块需要调用特定的function http docs python org dev library multiprocessing html multiprocessing freeze support在被 冻结 以生成 Wi
  • 如何在 openpyxl 中设置或更改表格的默认高度

    我想通过openpyxl更改表格高度 并且我希望首先默认一个更大的高度值 然后我可以设置自动换行以使我的表格更漂亮 但我不知道如何更改默认高度 唯一的到目前为止 我知道更改表格高度的方法是设置 row dimension idx heigh
  • 一起使用 Argparse 和 Json

    我是 Python 初学者 我想知道 Argparse 和 JSON 是否可以一起使用 说 我有变量p q r 我可以将它们添加到 argparse 中 parser add argument p param1 help x variabl
  • 以编程方式将列名称添加到 numpy ndarray

    我正在尝试将列名称添加到 numpy ndarray 然后按名称选择列 但这不起作用 我无法判断问题是在添加名称时出现 还是在稍后尝试调用它们时出现 这是我的代码 data np genfromtxt csv file delimiter
  • 如何解码 dtype=numpy.string_ 的 numpy 数组?

    我需要使用 Python 3 解码按以下方式编码的字符串 gt gt gt s numpy asarray numpy string hello nworld gt gt gt s array b hello nworld dtype S1
  • Docker 日志中的 Python 异常标记为流:stdout

    我想解析和处理来自 docker 容器的所有错误 但当我期望 stderr 时 Python 异常标记为 stdout 举个简单的例子app py raise Exception 然后我在 docker 容器中运行这个文件 但在 var l
  • 在 Python 中,如何获取特定文件中定义的类列表?

    如果一个文件myfile py包含 class A object Some implementation class B object Some implementation 我如何定义一个方法 以便在给定的情况下myfile py 它返回
  • 从 Apache 运行 python 脚本的最简单方法

    我花了很长时间试图弄清楚这一点 我基本上正在尝试开发一个网站 当用户单击特定按钮时 我必须在其中执行 python 脚本 在研究了 Stack Overflow 和 Google 之后 我需要配置 Apache 以便能够运行 CGI 脚本
  • 向伪 shell (pty) 发出命令

    我尝试使用 subprocess popen os spawn 来运行进程 但似乎需要伪终端 import pty master slave pty openpty os write master ls l 应该发送 ls l 到从属终端
  • python csv按列转换为字典

    是否可以将 csv 文件中的数据读取到字典中 使得列的第一行是键 同一列的其余行构成列表的值 例如 我有一个 csv 文件 strings numbers colors string1 1 blue string2 2 red string
  • 本地设置的 Cython 编译器指令是否影响一个或所有函数?

    我正在努力使用 Cython 加速一些 Python Numpy 代码 并且对 本地 设置 如定义的here http docs cython org en latest src reference compilation html在文档中
  • Melt() 函数复制数据集

    我有一个这样的表 id name doggo floofer puppo pupper 1 rowa NaN NaN NaN NaN 2 ray NaN NaN NaN NaN 3 emma NaN NaN NaN pupper 4 sop
  • bool() 和operator.truth() 有什么区别?

    bool https docs python org 3 library functions html bool and operator truth https docs python org 3 library operator htm
  • 将数组从 .npy 文件读入 Fortran 90

    我使用 Python 以二维数组 例如 X 的形式生成一些初始数据 然后使用 Fortran 对它们进行一些计算 最初 当数组大小约为 10 000 x 10 000 时 np savetxt 在速度方面表现良好 但是一旦我开始增加数组的维
  • 从 Flask 中的 S3 返回 PDF

    我正在尝试在 Flask 应用程序的浏览器中返回 PDF 我使用 AWS S3 来存储文件 并使用 boto3 作为与 S3 交互的 SDK 到目前为止我的代码是 s3 boto3 resource s3 aws access key id

随机推荐

  • 使用 :after 在元素后添加空格 (" ")

    我想在一些内容后面添加一个空格 但是content 似乎不起作用 这是我的代码 h2 after content 这不起作用 但是这确实有效 h2 after content 我究竟做错了什么 事实证明它需要通过转义的 unicode 来指
  • AJAX响应需要转换为blob

    我已经编写了ajax代码来设置请 求标头url并将其转换为 blob 并传递给函数showFile blob The blob然后以 pdf 格式处理并下载 这blob代码中获得的值如下undefined 有人可以帮我解决这个问题吗 var
  • 如何打印文件中的特定行

    我正在尝试打印文件 Scores 中的特定行 即选项 B 这是我的代码 print Option A Show all scores nOption B Show a record nOption Q Quit decision input
  • AWS Lambda 和 RDS 之间间歇性超时

    我们目前正在经历我只能描述为随机间歇AWS Lambda 和 RDS 之间的超时 部署我们的函数并成功运行它们后 它们可以随机切换到超时状态无需更改配置 值得注意的是 我们还在监视数据库连接 并可以确认我们没有遇到最大连接问题 以下是我们设
  • 表单右上角带有X的按钮,如何捕获此事件@C#

    当我使用 X 按钮关闭表单时会触发哪个事件 我想要仅在按下 X 按钮时触发的事件 我知道有一个 FormClosing 事件 但问题是每次关闭表单时都会触发它 当frm close 执行 我不希望这种情况发生 您可以检查 FormClosi
  • Angularjs 使用电子邮件类型重置表单字段

    在 AngularJs 中 似乎当您尝试通过将所有模型设置为空对象来 重置 表单时 如果输入是type email 这并没有得到清除 将其更改为type text 但是可以工作 但是您会在验证时丢失红色边框 是否有办法重置或清除电子邮件类型
  • 按元素长度对字符串数组进行排序

    拥有一个字符串数组 如何更新它 以便其元素按其长度排序 我正在尝试 string arr aa ss a abc arr arr OrderBy aux gt aux Length 所以 我会得到a aa ss abc 但它说 无法隐式转换
  • JVM JIT 诊断工具和优化技巧

    我听说过很多关于 JVM JIT 的内容can这样做 但没有看到很多关于如何分析 JIT 在程序的给定运行中实际执行的操作的信息 有很多使用技巧 XX PrintCompilation and XX PrintOptoAssembly但它会
  • 如何使用 Python Selenium Webdriver 在 Chrome 中加载默认配置文件?

    我想使用 Python 的 webdriver 启动 Chrome 及其默认配置文件 以便 cookie 和站点首选项在会话中保持不变 我怎样才能做到这一点 这就是它最终为我工作的原因 from selenium import webdri
  • 忘记旧的 WiFi Direct 连接

    有没有办法忘记旧的 WiFi Direct 连接 在代码中 我需要这个来更改谁成为群组所有者 我设置 groupOwnerIntent 15 但尚未成为组所有者 如果您只想断开与现有的连接WiFiP2p连接 然后只需调用WiFiP2pMan
  • 将大量数据加载到数组中的最快方法

    我在 stackexchange 中广泛搜索了一个将巨大 2GB dat 文件加载到 numpy 数组中的简洁解决方案 但没有找到合适的解决方案 到目前为止 我设法以非常快的方式 list f open myhugefile0 for li
  • C++ 在张量流中使用 Eigen

    张量流和特征值之间有什么关系 特别是关于tensor数据结构 有一些较旧的引文 例如 其中指出tensorflow正在广泛使用Eigen 据我所知 tensorflow人员已经扩展了Eigen代码 然而 最近的张量流文档似乎没有明确提及 E
  • SQL 2008 中的内存不足异常

    关于SQL Server 2008中Out of Memory异常 当我执行向表中插入数千行的大型查询时 执行此操作时发生的异常是 System OutOfMemoryException 根据一篇非常好的微软知识库文章 链接在这里 http
  • 如何获取 MongoDB 中的所有文档 ID?

    如何获取 MongoDB 中所有文档 ID 的数组 我只需要一组 id 但不需要文档内容 您可以通过调用在 Mongo shell 中执行此操作map http docs mongodb org manual reference metho
  • 为 MVC 应用程序添加尾部斜杠

    我正在构建一个基于 MVC 设计模式的应用程序 我希望我的 URL 如下 http example com page action http example com page action 我成功地让它与下面的代码一起工作 但如果 URL
  • 如果我要将文件内容读入数组,是否需要初始化数组?

    我正在初始化buf在立即用以下内容重写其内容之前不必要地全为零read exact fn parse
  • 在 Python 代码中使用 Git 命令

    我被要求编写一个脚本 从 Git 中提取最新代码 进行构建并执行一些自动化单元测试 我发现有两个内置的 Python 模块可以随时使用 用于与 Git 交互 GitPython and libgit2 我应该使用什么方法 模块 更简单的解决
  • 在输入类型=“文本”中键入时跟踪 onchange 的最佳方法?

    在我的经验中 input type text onchange事件通常仅在您离开后发生 blur 控制 有没有办法强制浏览器触发onchange每次textfield内容变化 如果不是 那么 手动 跟踪这个最优雅的方法是什么 Using o
  • 在 Razor 中将视图模型属性编码为 JavaScript

    我有一个简单的视图模型 public class IndexViewModel public bool ShowWelcomeMsg get set 在我看来 我需要 JS 中的这个属性 但这是不正确的 因为它输出False代替false但
  • 使用PyQt5嵌入动态条形图

    我在 python 中编写了以下代码 以在生成的 GUI 中显示条形图PyQt5 import sys from PyQt5 QtWidgets import QDialog QApplication QPushButton QVBoxLa