4

Recently I was wondering whether it was possible to automatically export plots from plotly. Unfortunately plotly's documentation is a joke and the module wants you to pay for a feature as basic as this. In the free version only automatic exports in non-vector formats (png) is possible. Here I want to present a workaround relying on phantomjs.

1 Answer 1

2

Step 1: Generate html file

import plotly.offline as py
import plotly.graph_objs as go

data = go.Scatter(x=[i for i in range(10)],
                  y=[i**2 for i in range(10)],
                  mode='lines')
layout = go.Layout(title="First Plot",
                   xaxis={'title':'x - axis'},
                   yaxis={'title':'y - axis'})
fig = dict(data=[data], layout=layout)

py.plot(fig,
        filename='temp.html',
        include_plotlyjs=True,
        output_type='file'
       )

Note: This includes a great part of plotly.js into the html file. This alone takes up some 2 MB. If need be, change include_plotlyjs to False and reference plotly.js inside the html file:

<script src="path/to/plotly.js"></script>

Step 2: Script for PhantomJS

Write a javascript file for phantomjs for exporting the PDF file:

var page = require('webpage').create();
var system = require('system');
var args = system.args;

page.viewportSize = { width: args[3], height: args[4] };
page.clipRect = { top: 0, left: 0, width: args[3], height: args[4] };

page.open(args[1], function() {
  page.render(args[2]);
  phantom.exit();
});

this expects 4 parameters: The path to the html file, the output file path, width and height of the output file.

Step3: Call PhantomJS script from python

import subprocess

xSize = 1280
ySize = 1024
subprocess.check_output(
    ['phantomjs', 'phantom_html_to_PDF.js', 'temp.html', out_path, str(x_Size), str(y_Size)])

#remove temporary html file
subprocess.check_output(['rm', 'temp.html])

This calls phantomjs and passes as arguments the path to the javascript from above, the path to the html file, the output file path and the width and height

I hope this is of use for someone

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for this! I can't get it to work with 3D images, though. Running phantomjs yields: TypeError: undefined is not an object (evaluating 't.glplot.canvas') and the generated pdf only shows title and legend and tells me that my browser does not support Webgl. Any ideas?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.