我想知道是否有人知道一个好方法(最好是内置方法,但我当然愿意写自己的方法)从Plotly离线客户端的HTML输出中获取<script>
和<div>
标签。
我已经熟悉散景并非常喜欢将它用于2D可视化,但我真的很想将Plotly与其3D可视化功能集成在一起。
如果您需要有关该项目的任何其他详细信息,请告诉我们。
如果你打电话:
plotly.offline.plot(data, filename='file.html')
它会创建一个名为file.html
的文件,并在您的Web浏览器中将其打开。但是,如果你这样做:
plotly.offline.plot(data, include_plotlyjs=False, output_type='div')
该调用将返回一个字符串,其中只包含创建图表所需的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>
请注意它只是一小部分html,你应该嵌入一个更大的页面。为此,我使用像Jinga2这样的标准模板引擎。
有了这个,您可以创建一个html页面,其中包含按您想要的方式排列的几个图表,甚至将其作为服务器响应返回到ajax调用,非常可爱。
更新:
请记住,您需要包含所有这些图表的plotly js文件才能工作。
你可以在放入div之前加入<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
。如果您将此js放在页面底部,则图表将无法使用。
对于死神回答的道歉真的想要留下一个评论给Fermin Silva留下(https://stackoverflow.com/a/38033016/2805700) - 但长期潜伏的潜伏者使我无法接受。
无论如何我有类似的需求并遇到了一个问题2.2.2
plotly.offline.plot(data, include_plotlyjs=False, output_type='div')
输出到div时,include_plotlyjs
参数被忽略。根据上面的评论,我找到了一个解决方法。基本上让情节绘图到文件,这确实尊重include_plotlyjs
参数。加载到美丽的汤,并注入到cdn上最新的plotly.js的链接。
import plotly
import bs4
# return as html fragment
# the include_plotlyjs argument seems to be
# ignored as it's included regardless when outputting to div
# found an open issue on here - https://github.com/plotly/plotly.py/issues/1043
plotly.offline.plot(
plot_output,
filename = filename,
config = plot_config,
include_plotlyjs = False,
auto_open = False,
)
# load the file
with open(filename) as inf:
txt = inf.read()
soup = bs4.BeautifulSoup(txt)
# add in the latest plot-ly js as per https://stackoverflow.com/a/38033016/2805700
js_src = soup.new_tag("script", src="https://cdn.plot.ly/plotly-latest.min.js")
# insert it into the document
soup.head.insert(0, js_src)
# save the file again
with open(filename, "w") as outf:
outf.write(str(soup))
干杯