python将绘图保存到本地文件并插入到html中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36262748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python save plotly plot to local file and insert into html
提问by cone001
I am using python and plotly to product interactive html report. This postgives a nice framework.
我正在使用 python 和 plotly 来生成交互式 html 报告。这篇文章提供了一个很好的框架。
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.
如果我在线生成绘图(通过 plotly),并将 url 插入到 html 文件中,它可以工作,但刷新图表需要很长时间。我想知道我是否可以离线生成图表并将其嵌入到 html 报告中,这样加载速度就不是问题了。
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?
我发现 plot offline 会为图表生成一个 html,但我不知道如何将它嵌入到另一个 html 中。任何人都可以帮忙吗?
采纳答案by JPW
Option 1: Use plotly's offline functionality in your Jupyter Notebook (I suppose you are using a Jupyter Notebook from the link you are providing). You can simply save the whole notebook as a HTML file. When I do this, the only external reference is to JQuery; plotly.js will be inlined in the HTML source.
选项 1:在您的 Jupyter Notebook 中使用 plotly 的离线功能(我想您正在使用您提供的链接中的 Jupyter Notebook)。您可以简单地将整个笔记本另存为 HTML 文件。当我这样做时,唯一的外部引用是 JQuery;plotly.js 将内联在 HTML 源代码中。
Option 2: The best way is probably to code directly against plotly's JavaScript library. Documentation for this can be found here: https://plot.ly/javascript/
选项 2:最好的方法可能是直接针对 plotly 的 JavaScript 库进行编码。可以在此处找到相关文档:https: //plot.ly/javascript/
Update: Calling an internal function has never been a good idea. I recommend to use the approach given by @Fermin Silva. In newer versions, there now is also a dedicated function for this: plotly.io.to_html
(see https://plotly.com/python-api-reference/generated/plotly.io.to_html.html)
更新:调用内部函数从来都不是一个好主意。我建议使用@Fermin Silva 给出的方法。在较新的版本中,现在还有一个专门的功能:(plotly.io.to_html
参见https://plotly.com/python-api-reference/generated/plotly.io.to_html.html)
Hacky Option 3(original version for reference only): If you really want to continue using Python, you can use some hack to extract the HTML it generates. You need some recent version of plotly (I tested it with plotly.__version__ == '1.9.6'
). Now, you can use an internal function to get the generated HTML:
Hacky Option 3(原始版本仅供参考):如果你真的想继续使用 Python,你可以使用一些 hack 来提取它生成的 HTML。你需要一些最新版本的 plotly(我用 测试过plotly.__version__ == '1.9.6'
)。现在,您可以使用内部函数来获取生成的 HTML:
from plotly.offline.offline import _plot_html
data_or_figure = [{"x": [1, 2, 3], "y": [3, 1, 6]}]
plot_html, plotdivid, width, height = _plot_html(
data_or_figure, False, "", True, '100%', 525)
print(plot_html)
You can simply paste the output somewhere in the body of your HTML document. Just make sure that you include a reference to plotly in the head:
您可以简单地将输出粘贴到 HTML 文档正文中的某个位置。只需确保在头部包含对 plotly 的引用:
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
Alternatively, you can also reference the exact plotly version you used to generate the HTML or inline the JavaScript source (which removes any external dependencies; be aware of the legal aspects however).
或者,您还可以引用用于生成 HTML 或内联 JavaScript 源代码的确切 plotly 版本(这会删除任何外部依赖项;但请注意法律方面)。
You end up with some HTML code like this:
你最终会得到一些这样的 HTML 代码:
<html>
<head>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<body>
<!-- Output from the Python script above: -->
<div id="7979e646-13e6-4f44-8d32-d8effc3816df" style="height: 525; width: 100%;" class="plotly-graph-div"></div><script type="text/javascript">window.PLOTLYENV=window.PLOTLYENV || {};window.PLOTLYENV.BASE_URL="https://plot.ly";Plotly.newPlot("7979e646-13e6-4f44-8d32-d8effc3816df", [{"x": [1, 2, 3], "y": [3, 1, 6]}], {}, {"showLink": false, "linkText": ""})</script>
</body>
</html>
Note: The underscore at the beginning of the function's name suggests that _plot_html
is not meant to be called from external code. So it is likely that this code will break with future versions of plotly.
注意:函数名称开头的下划线表明它_plot_html
不打算从外部代码调用。所以很可能这段代码会在未来版本的 plotly 中崩溃。
回答by Fermin Silva
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.
目前有一个更好的选择,即离线绘制到 div,而不是完整的 html。此解决方案不涉及任何黑客攻击。
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:
它会创建一个名为的文件file.html
并在您的 Web 浏览器中打开它。但是,如果您这样做:
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 的字符串,例如:
<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.
请注意,它只是您应该嵌入更大页面的 html 的一小部分。为此,我使用标准模板引擎,如 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.
有了这个,您可以创建一个 html 页面,其中包含多个按您想要的方式排列的图表,甚至可以将其作为服务器响应返回给 ajax 调用,非常棒。
Update:
更新:
Remember that you'll need to include the plotly js file for all these charts to work.
请记住,您需要包含 plotly js 文件才能使所有这些图表工作。
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.
就在放置你得到的 div 之前。如果你把这个js放在页面底部,图表将不起作用。
回答by David Marx
I wasn't able to get any of these solutions to work. My goal was to generate plots in one notebook and publish them in another, so persisting the plot HTML wasn't as important for me as simply having some method for serializing the plot to disk to be rebuilt somewhere else.
我无法让这些解决方案中的任何一个起作用。我的目标是在一个笔记本中生成绘图并在另一个笔记本中发布它们,因此保留绘图 HTML 对我来说并不像简单地使用某种方法将绘图序列化到磁盘以在其他地方重建那么重要。
The solution I came up with is to serialize the fig
object to JSON, and then use plotly's "json chart schema" to build the plot from JSON. This demo is all python, but it should be trivial to build a plot in HTML using this JSON-serialization strategy and invoking the plotly javascript library directly, if that's what you need.
我想出的解决方案是将fig
对象序列化为JSON,然后使用 plotly 的“json 图表模式”从 JSON 构建绘图。这个演示都是python,但是如果你需要的话,使用这种JSON序列化策略并直接调用plotly javascript库在HTML中构建一个绘图应该是微不足道的。
import numpy as np
import json
from plotly.utils import PlotlyJSONEncoder
from plotly.offline import download_plotlyjs, init_notebook_mode, iplot
import plotly.graph_objs as go
init_notebook_mode()
def plotlyfig2json(fig, fpath=None):
"""
Serialize a plotly figure object to JSON so it can be persisted to disk.
Figures persisted as JSON can be rebuilt using the plotly JSON chart API:
http://help.plot.ly/json-chart-schema/
If `fpath` is provided, JSON is written to file.
Modified from https://github.com/nteract/nteract/issues/1229
"""
redata = json.loads(json.dumps(fig.data, cls=PlotlyJSONEncoder))
relayout = json.loads(json.dumps(fig.layout, cls=PlotlyJSONEncoder))
fig_json=json.dumps({'data': redata,'layout': relayout})
if fpath:
with open(fpath, 'wb') as f:
f.write(fig_json)
else:
return fig_json
def plotlyfromjson(fpath):
"""Render a plotly figure from a json file"""
with open(fpath, 'r') as f:
v = json.loads(f.read())
fig = go.Figure(data=v['data'], layout=v['layout'])
iplot(fig, show_link=False)
## Minimial demo ##
n = 1000
trace = go.Scatter(
x = np.random.randn(n),
y = np.random.randn(n),
mode = 'markers')
fig = go.Figure(data=[trace])
#iplot(fig)
plotlyfig2json(fig, 'myfile.json')
plotlyfromjson('myfile.json')
EDIT: Per discussion on the associated github issue, this is probably the current best approach.
编辑:根据对相关 github问题的讨论,这可能是当前最好的方法。
回答by Maximilian Peters
In addition to the other answers, another possible solution is to use to_json()
on the plotly figure.
除了其他答案之外,另一种可能的解决方案是to_json()
在情节图上使用。
No need for custom JSON serializer or use of internal solutions.
无需自定义 JSON 序列化程序或使用内部解决方案。
import plotly
# create a simple plot
bar = plotly.graph_objs.Bar(x=['giraffes', 'orangutans', 'monkeys'],
y=[20, 14, 23])
layout = plotly.graph_objs.Layout()
fig = plotly.graph_objs.Figure([bar], layout)
# convert it to JSON
fig_json = fig.to_json()
# a simple HTML template
template = """<html>
<head>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<body>
<div id='divPlotly'></div>
<script>
var plotly_data = {}
Plotly.react('divPlotly', plotly_data.data, plotly_data.layout);
</script>
</body>
</html>"""
# write the JSON to the HTML template
with open('new_plot.html', 'w') as f:
f.write(template.format(fig_json))
回答by Paul Rougieux
You can also use an iframe according to an answer to the question how to embed html into ipython output?
您还可以根据问题how to embed html into ipython output的答案使用 iframe ?
plotly.offline.plot(fig, filename='figure.html',validate=False)
from IPython.display import IFrame
IFrame(src='./figure.html', width=1000, height=600)
回答by sohail
To improvise the below code you could just call, to_plotly_json() for ex:,
要即兴编写以下代码,您可以调用 to_plotly_json() 例如:,
def plotlyfig2json(fig, fpath=None):
"""
Serialize a plotly figure object to JSON so it can be persisted to disk.
Figures persisted as JSON can be rebuilt using the plotly JSON chart API:
http://help.plot.ly/json-chart-schema/
If `fpath` is provided, JSON is written to file.
Modified from https://github.com/nteract/nteract/issues/1229
"""
redata = json.loads(json.dumps(fig.data, cls=PlotlyJSONEncoder))
relayout = json.loads(json.dumps(fig.layout, cls=PlotlyJSONEncoder))
fig_json=json.dumps({'data': redata,'layout': relayout})
if fpath:
with open(fpath, 'wb') as f:
f.write(fig_json)
else:
return fig_json
--------------------------------------------
Simple way:
fig = go.Figure(data=['data'], layout=['layout'])
fig.to_plotly_json()
回答by Anass Lahrech
I have recently needed to export Plotly Chart to HTML files.
我最近需要将 Plotly Chart 导出到 HTML 文件。
Here is the simple proper way to do it in 2019.
这是在 2019 年执行此操作的简单正确方法。
import plotly.offline
plot(figure, "file.html")
回答by VarunVk
Easiest way is to use piofrom plotly
最简单的方法是从 plotly使用pio
import plotly.io as pio
pio.write_html(fig, file='Name.html', auto_open=True)
I have used it a ton of lots to store my graphs before important meetings
在重要会议之前,我已经大量使用它来存储我的图表