Can I embed plotly graphs (offline) in my PyQt4 application?

I once tried using the:

import plotly.offline as plt
.
.
.
plt.plot(fig, filename=testName + '__plot.html')

and then tried to generate a plot.. this gave me an HTML file which then I also tried putting on a QWebView as its URL property [just to see if it renders].

Here is the image for your reference:

Render :: Plotly Offline :: QtWebView


You can use QWebEngineView from the QWebEngineWidgets module (I used PyQt5 here but I guess it'll also work for PyQt4). You create html code using plotly.offline.plot and set this as the html text for your instance of QWebEngineView. If you specify output_type='div' it will give you directly a string. I do not know why, but in my case it only worked with include_plotlyjs='cdn', but in that case you need to be on the internet for it to work according to the plotly documentation. By doing it that way the plot stays interactive also in your PyQt application.

from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtWidgets import QApplication, QMainWindow
from plotly.graph_objects import Figure, Scatter
import plotly

import numpy as np


class MainWindow(QMainWindow):

    def __init__(self):

        super(MainWindow, self).__init__()

        # some example data
        x = np.arange(1000)
        y = x**2

        # create the plotly figure
        fig = Figure(Scatter(x=x, y=y))

        # we create html code of the figure
        html = '<html><body>'
        html += plotly.offline.plot(fig, output_type='div', include_plotlyjs='cdn')
        html += '</body></html>'

        # we create an instance of QWebEngineView and set the html code
        plot_widget = QWebEngineView()
        plot_widget.setHtml(html)

        # set the QWebEngineView instance as main widget
        self.setCentralWidget(plot_widget)


if __name__ == '__main__':
    app = QApplication([])
    window = MainWindow()
    window.show()
    app.exec_()