首页 > 解决方案 > 如何在pyqt5中嵌入绘图图?

问题描述

我用谷歌搜索并找到了两个代码,我得到了相同的错误。有什么可以帮忙的吗?

from PyQt5.QtWebEngineWidgets import QWebEngineView

ImportError: QtWebEngineWidgets must be imported before a QCoreApplication instance is created

第一个代码: https ://github.com/plotly/plotly.py/issues/716

import plotly.offline as po
import plotly.graph_objs as go

from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5 import QtCore, QtWidgets
import sys


def show_qt(fig):
    raw_html = '<html><head><meta charset="utf-8" />'
    raw_html += '<script src="https://cdn.plot.ly/plotly-latest.min.js"></script></head>'
    raw_html += '<body>'
    raw_html += po.plot(fig, include_plotlyjs=False, output_type='div')
    raw_html += '</body></html>'

    fig_view = QWebEngineView()
    # setHtml has a 2MB size limit, need to switch to setUrl on tmp file
    # for large figures.
    fig_view.setHtml(raw_html)
    fig_view.show()
    fig_view.raise_()
    return fig_view


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

    fig = go.Figure(data=[{'type': 'scattergl', 'y': [2, 1, 3, 1]}])
    fig_view = show_qt(fig)
    sys.exit(app.exec_())

第二个代码:

如何将绘图作为 PyQt5 小部件?

from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets
import plotly.express as px


class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.button = QtWidgets.QPushButton('Plot', self)
        self.browser = QtWebEngineWidgets.QWebEngineView(self)

        vlayout = QtWidgets.QVBoxLayout(self)
        vlayout.addWidget(self.button, alignment=QtCore.Qt.AlignHCenter)
        vlayout.addWidget(self.browser)

        self.button.clicked.connect(self.show_graph)
        self.resize(1000,800)

    def show_graph(self):
        df = px.data.tips()
        fig = px.box(df, x="day", y="total_bill", color="smoker")
        fig.update_traces(quartilemethod="exclusive") # or "inclusive", or "linear" by default
        self.browser.setHtml(fig.to_html(include_plotlyjs='cdn'))

if __name__ == "__main__":
    app = QtWidgets.QApplication([])
    widget = Widget()
    widget.show()
    app.exec()

标签: pythonpyqt5spyderplotly-pythonqwebengineview

解决方案


推荐阅读