KcH
KcH

Reputation: 3502

How to save the plot in image format

Here 'graphJSON' is a variable used for plotting the graph and how can i capture(image format) the graph using this variable?

graphJSON = json.dumps(data, cls=plotly.utils.PlotlyJSONEncoder)
plotly.io.to_image(graphJSON, format=None,
                   scale=None, width=None, height=None)

Upvotes: 2

Views: 3754

Answers (2)

cyotani
cyotani

Reputation: 61

The marked answer is correct. This is just an FYI that you can simplify the fig to png_base64 conversion by converting the figure directly to an image.

This:

png_base64 = base64.b64encode(fig.to_image()).decode('ascii')

Instead of this:

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

Upvotes: 4

Maximilian Peters
Maximilian Peters

Reputation: 31649

  • Install plotly-orca
  • Create your plotly figure
  • Convert the figure to PNG
  • Convert the binary PNG to base64 encoded bytes
  • Decode the base64 bytes to ascii and pass them to your Jinja2 template

Full code

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

Upvotes: 3

Related Questions