Saving or downloading plotly iplot images on Google Colaboratory

余生长醉 提交于 2019-12-24 10:48:39

问题


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

回答1:


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

!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 this is done you can use this 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')


来源:https://stackoverflow.com/questions/57262385/saving-or-downloading-plotly-iplot-images-on-google-colaboratory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!