Search code examples
downloadplotlygoogle-colaboratory

Saving or downloading plotly iplot images on Google Colaboratory


I have been attempting to download a plot created using plotly on google colaboratory. So far this is what I have attempted:

I have tried changing

files.download('foo.svg')

to

files.download('foo')

and I still get no results. I navigated to the files on Google colab and nothing shows there

import numpy as np 
import pandas as pd
from plotly.offline import iplot
import plotly.graph_objs as go
from google.colab import files

def enable_plotly_in_cell():
  import IPython
  from plotly.offline import init_notebook_mode
  display(IPython.core.display.HTML('''<script src="/static/components/requirejs/require.js"></script>'''))
  init_notebook_mode(connected=False)

#this actually shows the plot 
enable_plotly_in_cell()

N = 500
x = np.linspace(0, 1, N)
y = np.random.randn(N)
df = pd.DataFrame({'x': x, 'y': y})
df.head()

data = [
    go.Scatter(
        x=df['x'], # assign x as the dataframe column 'x'
        y=df['y']
    )
]

iplot(data,image = 'svg', filename = 'foo')

files.download('foo.svg')

This is the error I am getting:

OSErrorTraceback (most recent call last)
<ipython-input-18-31523eb02a59> in <module>()
     29 iplot(data,image = 'svg', filename = 'foo')
     30 
---> 31 files.download('foo.svg')
     32 

/usr/local/lib/python2.7/dist-packages/google/colab/files.pyc in download(filename)
    140     msg = 'Cannot find file: {}'.format(filename)
    141     if _six.PY2:
--> 142       raise OSError(msg)
    143     else:
    144       raise FileNotFoundError(msg)  # pylint: disable=undefined-variable

OSError: Cannot find file: foo.svg

Solution

  • To save vector or raster images (e.g. SVGs or PNGs) from Plotly figures you need to have Kaleido (preferred) or Orca (legacy) installed, which is actually possible using the following commands in Colab:

    Kaleido:

    !pip install kaleido
    

    Orca:

    !pip install plotly>=4.0.0
    !wget https://github.com/plotly/orca/releases/download/v1.2.1/orca-1.2.1-x86_64.AppImage -O /usr/local/bin/orca
    !chmod +x /usr/local/bin/orca
    !apt-get install xvfb libgtk2.0-0 libgconf-2-4
    

    Once either of the above is done you can use the following code to make, show and export a figure (using plotly version 4):

    import plotly.graph_objects as go
    fig = go.Figure( go.Scatter(x=[1,2,3], y=[1,3,2] ) )
    fig.show()
    fig.write_image("image.svg")
    fig.write_image("image.png")
    

    The files can then be downloaded with:

    from google.colab import files
    files.download('image.svg')
    files.download('image.png')