使用Google Colaboratory的Plotly笔记本模式

51

我正在使用Plotly笔记本模式尝试Colaboratory - 我打开一个新的笔记本,从Plotly的文档中复制并粘贴以下简单示例,但没有看到输出。输出空间中有一个大的空白,通常会显示图形的地方。

在我的本地笔记本中,这个例子可以正常工作(这是较新版本的Plotly,但根据他们的文档,离线模式应该与Google Colab版本兼容),有什么想法吗?

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")
})
5个回答

60

plotly 版本 4.x

从版本 4 开始,plotly 渲染器支持 Colab,因此以下代码足以在 Colab、Jupyter (以及其他笔记本,如 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版本3.x

以下是在Colab中使用Plotly的示例。(Plotly需要自定义初始化。)

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

您需要定义此函数:

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>
        '''))

并在每个离线绘图单元格中调用它:

configure_plotly_browser_state()

谢谢!看起来 configure_plotly_browser_state() 需要在每个单元格中调用,如果我想包含一个图表 - 这是正确的吗?你知道是否可以为整个笔记本初始化吗? - elz
1
Plotly确实需要为每个单元格进行初始化。在Colab中,每个单元格都在一个iframe沙盒中呈现,因此输出之间没有共享的初始化状态。 - Bob Smith
我将函数本身添加到答案中。还要注意,您需要引用“plotly-latest.min.js”,而不是笔记本中的“plotly-1.5.1.min.js”。 - Max Ghenis
3
即使使用了版本4.6.0,plotly对我来说仍然无法工作,所以我不得不采用Pratik Parmar的答案 - Zaccharie Ramzi
即使在plotly 4.x版本中,每个单元格仍需要调用初始化函数。然而,@Remis Haroon - رامز的解决方案确实很好。 - Selfcontrol7

46

只需在fig.show(renderer="colab")中将参数renderer的值设置为"colab"即可。

示例:

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")

在这里输入图片描述


谢谢,@RemisHaroon 提供了相当高效的解决方案。 - PN10
此解决方案适用于 plotly 版本 4.x。 - Selfcontrol7

27
解决方案
import plotly.io as pio
pio.renderers.default = "colab"

你需要更改默认的渲染器。以下是文档中的摘录。 https://plot.ly/python/renderers/#setting-the-default-renderer

当前和可用的渲染器是使用 plotly.io.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']

18
你需要添加一个方法才能在Colab中使用Plotly。
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)

这个方法必须针对每个显示Plotly图表的单元格执行。

示例:

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)

参考资料:https://colab.research.google.com/notebooks/charts.ipynb#scrollTo=WWbPMtDkO4xg


2
这太棒了。在尝试了所有其他解决方案之后,这是唯一有效的一个。做得很好,感谢您的发现和发布。 - double0darbo

15

configure_plotly_browser_state() 可以通过使用 IPython 的 pre_run_cell 钩子在运行每个单元格之前执行:



import IPython

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



2
我得到了以下错误信息:> 追溯(最近的调用最后) <ipython-input-19-ac1874a09e95> in <module>() 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,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):值错误:列表中没有x。 - Max Ghenis
当您在plotly的API上进行包装时,它会变得优雅,其中您可以根据条件初始化colab,当检测到在colab运行时(get_ipython().__class__.__module__ == "google.colab._shell"),否则不进行初始化。 - matanster
1
应该是 register 调用吧? - tomwesolowski

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接