【问题标题】:How to have plotly graph as PyQt5 widget? [duplicate]如何将绘图作为 PyQt5 小部件? [复制]
【发布时间】:2020-06-16 17:05:33
【问题描述】:

我正在做 GUI,其中应该有一个带有以下情节的小部件:

import plotly.express as px
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
fig.show() 

你能提出一些建议吗?

【问题讨论】:

    标签: python pyqt5


    【解决方案1】:

    您可以使用QtWebEngineWidgets.QWebEngineView 小部件来显示该图。您可能需要先安装 PyQtWebEngine 软件包。这是一个小例子:

    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()
    

    【讨论】:

    • 感谢 Heike,我运行它并得到 ImportError 的错误:在创建 QCoreApplication 实例之前必须导入 QtWebEngineWidgets。有什么建议吗?谢谢
    • 看起来您在导入 QtWebEngineWidgets 之前正在初始化 QApplication 实例
    • 对 Heike,但是如何更改您的代码以使其工作?我使用了与上面显示的相同的代码。我什至从 PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets 到 beforeapp = QtWidgets.QApplication([]) inside if name == "main": ,它仍然无法正常工作?谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-13
    • 1970-01-01
    相关资源
    最近更新 更多