这里的“ graphJSON”是用于绘制图形的变量,我如何使用此变量捕获(图像格式)图形?
graphJSON = json.dumps(data, cls=plotly.utils.PlotlyJSONEncoder)
plotly.io.to_image(graphJSON, format=None,
scale=None, width=None, height=None)
答案 0 :(得分:0)
ascii
,并将其传递到您的Jinja2模板完整代码
import plotly
import base64
import jinja2
# create the graph
scatter = plotly.graph_objs.Scatter(x=[1, 2, 3], y=[2, 1, 3])
layout = plotly.graph_objs.Layout()
fig = plotly.graph_objs.Figure([scatter], layout)
# convert graph to JSON
fig_json = fig.to_json()
# convert graph to PNG and encode it
png = plotly.io.to_image(fig)
png_base64 = base64.b64encode(png).decode('ascii')
# definition of the Jinja2 template
template = """<html>
<head>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<body>
<img src="data:image/png;base64,{{ png_base64 }}" />
<div id='divPlotly'></div>
<script>
var plotly_data = {{ plotly_data }}
Plotly.react('divPlotly', plotly_data.data, plotly_data.layout);
</script>
</body>
</html>"""
# generate the HTML page
with open('new_plot.html', 'w') as f:
f.write(jinja2.Template(template).render(png_base64=png_base64,
plotly_data=fig_json))