python - 如何在框架内绘制直方图?

标签 python matplotlib pyqt4

到目前为止,我正在运行 plt.hist 函数并将结果保存在图像中,然后在 mdiArea 中使用以下代码进行绘图

def test(self):
    self.result = QtGui.QMdiSubWindow()
    self.result.setObjectName(_fromUtf8("subWindow"))
    pixmap = QtGui.QPixmap(_fromUtf8('Result.png'))
    graphicsView = QtGui.QGraphicsView(self.result)
    self.mdiArea.addSubWindow(self.result)
    graphicsView.setGeometry(QtCore.QRect(30, 30, pixmap.width() + 10, pixmap.height() + 10))
    graphicsView.setObjectName(_fromUtf8("graphicView"))
    scene = QtGui.QGraphicsScene()
    scene.addPixmap(pixmap)
    scene.setSceneRect(QtCore.QRectF(pixmap.rect()))
    scene.update()
    graphicsView.setScene(scene)
    self.result.resize(pixmap.width() + 60, pixmap.height() + 60)
    self.result.setWindowTitle('Results')
    self.result.show()

但是当我绘制大数据集时,直方图变得太小。有没有办法直接在 de mdiArea

内使用 plt.hist 进行绘图

我有这个: enter image description here

我想把它放在窗口内:

enter image description here

顺便问一下,有没有更好的方法在直方图中显示这些数据?

最佳答案

您必须使用Qt4后端的FigureCanvas创建 Canvas (1),在下面的代码中我展示了一个示例:

import numpy as np

from PyQt4 import QtCore, QtGui

from matplotlib.backends.backend_qt4agg import (
    FigureCanvas,
    NavigationToolbar2QT as NavigationToolbar,
)
from matplotlib.figure import Figure


class ApplicationWindow(QtGui.QMainWindow):
    def __init__(self):
        super().__init__()
        self.mdiArea = QtGui.QMdiArea()
        self.setCentralWidget(self.mdiArea)

        mu, sigma = 100, 15
        x = mu + sigma * np.random.randn(10000)

        self._canvas = FigureCanvas(Figure(figsize=(5, 3)))
        self._ax = self._canvas.figure.subplots()
        n, bins, patches = self._ax.hist(
            x, 50, density=1, facecolor="green", alpha=0.75
        )
        self._ax.set_xlabel("Smarts")
        self._ax.set_ylabel("Probability")
        self._ax.set_title(r"$\mathrm{Histogram\ of\ IQ:}\ \mu=100,\ \sigma=15$")
        self._ax.axis([40, 160, 0, 0.03])
        self._ax.grid(True)

        widget = QtGui.QMainWindow()
        widget.setCentralWidget(self._canvas)
        widget.addToolBar(
            QtCore.Qt.BottomToolBarArea, NavigationToolbar(self._canvas, self)
        )
        sub_window = QtGui.QMdiSubWindow()
        sub_window.setWidget(widget)
        self.mdiArea.addSubWindow(sub_window)


if __name__ == "__main__":
    import sys

    qapp = QtGui.QApplication(sys.argv)
    app = ApplicationWindow()
    app.show()
    sys.exit(qapp.exec_())

enter image description here


(1) Embedding in Qt

关于python - 如何在框架内绘制直方图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57367474/

相关文章:

python - 使用多个命令运行 for 循环文件,当第一个命令前一个文件完成时运行下一个文件

python - 返回包含两个或多个关键字的行

Javascript 模板字符串占位符

python - 从 python 中的 timedelta64 对象创建箱线图

python - 如何为pyqt项目创建windows安装程序

internationalization - 使用 PyQt4 进行国际化的最佳实践

python - 从多个表查询Python Mysql Connector

matplotlib - 如何绘制远程图像(来自 http url)

python - 绘制 NetworkX Girvan-Newman 算法找到的社区的树状图

python - 为什么我需要保留一个指向我的 QWidget 的变量?