javascriptpythonplotlypyqt5qwebview

open plotly in qwebview in interactive mode


I'm using plotly library in offline mode with python and what I'm trying to do is to create some plot, save them as local html and load in a second moment into a QWebView.

This is the code for a boxplot with a dummy variable:

from PyQt5.QtWebKitWidgets import QWebView
import plotly
import plotly.graph_objs as go

x1 = [10, 3, 4, 5, 20, 4, 3]

trace1 = go.Box(
x = x1)

layout = go.Layout(
    showlegend = True
)


data = [trace1]
fig = go.Figure(data=data, layout = layout)

fn = '/home/matteo/plot.html'
plotly.offline.plot(fig, filename = fn, 
auto_open = False)

view = QWebView()
view.load(QUrl.fromLocalFile(fn))
view.show()

I'm facing 2 main problems:

  1. if I let the code as it is, the QWebView won't show anything like in the image: enter image description here

  2. if I open the html file with the standard browser (Firefox for example), I can see and interact with the plot, and that's fine. But if I save the html page from the browser in a local directory and try to load the saved file into the QWebView I can see the plot, but cannot interact with it (maybe for some Javascript missing?!):

enter image description here

Anybody has some ideas how to embed an interactive offline made chart into a QWebView?


Solution

  • Ok, I should have find what the problem is.

    Is seems that QWebView has some difficulties to load the local file because it is too heavy (about 2mb for simple plot).

    So I used the option to not include the javascript when saving the local file and to load the javascript in a second moment thanks, as described here.

    In other words, create the initial html tags, include the result of the figure generated by plotly without the whole javascript code, and include the link of the javascript.

    In this way the file is super light and QWebView does not have issue to open it.

    # create the initial html code
    raw_html = '<head><meta charset="utf-8" /></head>''<head><meta charset="utf-8" /><script src="https://cdn.plot.ly/plotly-latest.min.js"></script></head>'
    
    # call the plot method without all the javascript code
    raw_html += plotly.offline.plot(fig, filename = fn, include_plotlyjs=False)
    
    # close the body and html tags
    raw_html += '</body></html>'