6

I am doing GUI where there should be a widget with the following plot:

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

Can you suggest something?

1 Answers1

13

You can use a QtWebEngineWidgets.QWebEngineView widget to show the figure. You might need to install the PyQtWebEngine package first. Here is a small example:

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
  • 24,102
  • 2
  • 31
  • 45
  • Thanks Heike, I ran it and got and error of ImportError: QtWebEngineWidgets must be imported before a QCoreApplication instance is created. any suggestion? Thanks – roudan Sep 19 '21 at 16:50
  • It looks like you are initialising the `QApplication` instance before importing `QtWebEngineWidgets` – Heike Sep 20 '21 at 05:14
  • right Heike, but how to change your code to make it work? I used the same code as you shown above. I even move from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets to beforeapp = QtWidgets.QApplication([]) inside if __name__ == "__main__":, and it still not working? Thanks – roudan Sep 21 '21 at 02:00
  • https://stackoverflow.com/a/54947671/3059024 – CiaranWelsh Jun 13 '22 at 21:17