Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
718 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...