Black Lives Matter. Please consider donating to Black Girls Code today.

Save image as png or svg

Hi all,

the question is trivial, but cannot solve it alone. What I would like to achieve is to save in the same path, and at the same time, the html and a png image of the plot.

For instance, with this small piece of code:

data = [go.Scatter(x=[1, 2, 3], y=[3, 2, 6])]
plotly.offline.plot(data, filename='/tmp/my-plot', image='svg')

I would like to auto-open the html (correctly done) and saving my-plot.svg in the /tmp directory but silently. At the moment, when running the code, the browser is asking me where to save the svg image.

Is it possible?


1 Like

Two possible issues:

  • I think this could be a browser setting. For example, see these instructions on firefox settings. Using chromium doesn’t ask me, for example, it just downloads the file.

  • Secondly, note that the arg is image_filename; currently filename is setting the name of the .html to save, not the image. See the plotly.offline reference here.

That said, I haven’t been able to get the files to save anywhere other than the browser download path. That said, you could import copyfile (or just move) from shutil after it’s downloaded? For example:

import os
import plotly
import plotly.graph_objs as go
import time
from shutil import copyfile

img_name = 'my-plot'
dload = os.path.expanduser('~/Downloads')
save_dir = '/tmp'

data = [go.Scatter(x=[1, 2, 3], y=[3, 2, 6])]

plotly.offline.plot(data, image_filename=img_name, image='svg')

### might need to wait for plot to download before copying

copyfile('{}/{}.svg'.format(dload, img_name),
         '{}/{}.svg'.format(save_dir, img_name))

This is the canonical documentation page for this issue: