51

I am am trying out colaboratory with plotly notebook mode - I open a new notebook, copy and paste the following simple example from plotly's documentation, but don't see an output. There is a large blank in the output space where the plot whould normally be.

This works fine in my local notebook (which is a newer version of plotly, but per their docs offline mode should work with the google colab version) Any ideas?

import plotly
from plotly.graph_objs import Scatter, Layout

plotly.offline.init_notebook_mode(connected=True)

plotly.offline.iplot({
    "data": [Scatter(x=[1, 2, 3, 4], y=[4, 3, 2, 1])],
    "layout": Layout(title="hello world")
})
elz
  • 5,338
  • 3
  • 28
  • 30

5 Answers5

59

plotly version 4.x

As of version 4, plotly renderers know about Colab, so the following is sufficient to display a figure in both Colab and Jupyter (and other notebooks like Kaggle, Azure, nteract):

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

plotly version 3.x

Here's an example showing the use of Plotly in Colab. (Plotly requires custom initialization.)

https://colab.research.google.com/notebook#fileId=14oudHx5e5r7hm1QcbZ24FVHXgVPD0k8f

You need to define this function:

def configure_plotly_browser_state():
  import IPython
  display(IPython.core.display.HTML('''
        <script src="/static/components/requirejs/require.js"></script>
        <script>
          requirejs.config({
            paths: {
              base: '/static/base',
              plotly: 'https://cdn.plot.ly/plotly-latest.min.js?noext',
            },
          });
        </script>
        '''))

And call it in each offline plotting cell:

configure_plotly_browser_state()
nicolaskruchten
  • 26,384
  • 8
  • 83
  • 101
Bob Smith
  • 36,107
  • 11
  • 98
  • 91
  • Thanks! It appears that `configure_plotly_browser_state()` needs to be called in every cell where I want to include a plot - is that correct? Do you know if its possible to initialize for the entire notebook? – elz Nov 13 '17 at 15:29
  • 1
    Plotly does indeed need to be initialized for each cell. In Colab, each cell is rendered in an `iframe` sandbox, so there's no shared initialization state between outputs. – Bob Smith Nov 13 '17 at 17:08
  • I added the function itself to the answer. Note also that you need to reference `plotly-latest.min.js` rather than `plotly-1.5.1.min.js` as is in the notebook. – Max Ghenis Jul 04 '18 at 01:46
  • 3
    `plotly` wasn't working for me even with version 4.6.0, so I had to resort to use Pratik Parmar's [answer](https://stackoverflow.com/a/54771665/4332585) – Zaccharie Ramzi Apr 08 '20 at 14:27
  • Even on plotly version 4.x, there is need to call the initialization function in each cell. However, @Remis Haroon - رامز solution works well indeed. – Selfcontrol7 Oct 07 '21 at 11:55
46

simply pass "colab" as the value for the parameter renderer in fig.show(renderer="colab")

example :

import plotly.graph_objects as go
fig = go.Figure(
    data=[go.Bar(y=[2, 1, 3])],
    layout_title_text="A Figure Displayed with the 'colab' Renderer"
)
fig.show(renderer="colab")

enter image description here

Remis Haroon - رامز
  • 3,304
  • 4
  • 34
  • 62
27

Solution

import plotly.io as pio
pio.renderers.default = "colab"

You need to change the default render. Here is an excerpt from the documentation. https://plot.ly/python/renderers/#setting-the-default-renderer

The current and available renderers are configured using the plotly.io.renderers configuration object. Display this object to see the current default renderer and the list of all available renderers.

>>>import plotly.io as pio
>>>pio.renderers


Renderers configuration
    -----------------------
        Default renderer: 'notebook_connected'
        Available renderers:
            ['plotly_mimetype', 'jupyterlab', 'nteract', 'vscode',
             'notebook', 'notebook_connected', 'kaggle', 'azure', 'colab',
             'cocalc', 'databricks', 'json', 'png', 'jpeg', 'jpg', 'svg',
             'pdf', 'browser', 'firefox', 'chrome', 'chromium', 'iframe',
             'iframe_connected', 'sphinx_gallery']
Marat Idrisov
  • 390
  • 6
  • 8
17

You need to add a method in order to use Plotly in Colab.

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 method must be executed for every cell which is displaying a Plotly graph.

Sample:

from plotly.offline import iplot
import plotly.graph_objs as go

enable_plotly_in_cell()

data = [
    go.Contour(
        z=[[10, 10.625, 12.5, 15.625, 20],
           [5.625, 6.25, 8.125, 11.25, 15.625],
           [2.5, 3.125, 5., 8.125, 12.5],
           [0.625, 1.25, 3.125, 6.25, 10.625],
           [0, 0.625, 2.5, 5.625, 10]]
    )
]
iplot(data)

Reference: https://colab.research.google.com/notebooks/charts.ipynb#scrollTo=WWbPMtDkO4xg

Pratik Parmar
  • 321
  • 3
  • 12
  • 2
    This is excellent. Having tried all other solutions, this is the only one that worked. Great job, and thanks for finding and posting it. – double0darbo May 12 '21 at 18:27
15

configure_plotly_browser_state() can be executed before running every cell by using IPython's pre_run_cell hook:

import IPython

IPython.get_ipython().events.register('pre_run_cell', configure_plotly_browser_state)

Ofir Moses
  • 23
  • 5
blois
  • 1,506
  • 11
  • 6
  • 2
    I get this: > Traceback (most recent call last) in () 1 import IPython ----> 2 IPython.get_ipython().events.unregister('pre_run_cell', configure_plotly_browser_state) /usr/local/lib/python3.6/dist-packages/IPython/core/events.py in unregister(self, event, function) 62 def unregister(self, event, function): 63 """Remove a callback from the given event.""" ---> 64 self.callbacks[event].remove(function) 65 66 def trigger(self, event, *args, **kwargs): ValueError: list.remove(x): x not in list – Max Ghenis Jul 04 '18 at 01:52
  • It gets elegant when you wrap over plotly's API where you conditionally initialize for colab when running on the colab runtime is detected (`get_ipython().__class__.__module__ == "google.colab._shell"`) and not otherwise. – matanster Nov 22 '18 at 18:29
  • 1
    Shouldn't it be `register` call? – tomwesolowski Jan 13 '19 at 22:20