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
106 views
in Technique[技术] by (71.8m points)

python save plotly plot to local file and insert into html

I am using python and plotly to product interactive html report. This post gives a nice framework.

If I produce the plot(via plotly) online, and insert the url into the html file, it works but refreshing the charts takes a long time. I wonder if I could produce the chart offline and have it embedded in the html report, so that loading speed is not a problem.

I find plot offline would generate a html for the chart, but I don't know how to embed it in another html. Anyone could help?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

There is a better alternative as of right now, that is to do offline plotting into a div, rather than a full html. This solution does not involve any hacks.

If you call:

plotly.offline.plot(data, filename='file.html')

It creates a file named file.html and opens it up in your web browser. However, if you do:

plotly.offline.plot(data, include_plotlyjs=False, output_type='div')

the call will return a string with only the div required to create the data, for example:

<div id="82072c0d-ba8d-4e86-b000-0892be065ca8" style="height: 100%; width: 100%;" class="plotly-graph-div"></div>
<script type="text/javascript">window.PLOTLYENV=window.PLOTLYENV || {};window.PLOTLYENV.BASE_URL="https://plot.ly";Plotly.newPlot("82072c0d-ba8d-4e86-b000-0892be065ca8", 
[{"y": ..bunch of data..., "x": ..lots of data.., {"showlegend": true, "title": "the title", "xaxis": {"zeroline": true, "showline": true}, 
"yaxis": {"zeroline": true, "showline": true, "range": [0, 22.63852380952382]}}, {"linkText": "Export to plot.ly", "showLink": true})</script>

Notice how its just a tiny portion of an html that you are supposed to embed in a bigger page. For that I use a standard template engine like Jinga2.

With this you can create one html page with several charts arranged the way you want, and even return it as a server response to an ajax call, pretty sweet.

Update:

Remember that you'll need to include the plotly js file for all these charts to work.

You could include

<script src="https://cdn.plot.ly/plotly-latest.min.js"></script> 

just before putting the div you got. If you put this js at the bottom of the page, the charts won't work.


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

...