【问题标题】:Plotly notebook mode with google colaboratoryPlotly 与谷歌合作的笔记本模式
【发布时间】:2018-04-24 03:46:15
【问题描述】:

我正在尝试使用 plotly 笔记本模式进行协作 - 我打开一个新笔记本,从 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")
})

【问题讨论】:

    标签: plotly google-colaboratory


    【解决方案1】:

    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() 需要在我想要包含绘图的每个单元格中调用 - 对吗?你知道它是否可以为整个笔记本初始化吗?
    • Plotly 确实需要为每个单元格初始化。在 Colab 中,每个单元格都在 iframe 沙箱中呈现,因此输出之间没有共享初始化状态。
    • 我将函数本身添加到答案中。另请注意,您需要引用plotly-latest.min.js 而不是笔记本中的plotly-1.5.1.min.js
    • plotly 即使是 4.6.0 版也无法为我工作,所以我不得不求助于 Pratik Parmar 的 answer
    • 即使在 plotly 4.x 版本上,也需要在每个单元格中调用初始化函数。但是,@Remis Haroon - رامز 解决方案确实效果很好。
    【解决方案2】:

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

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

    【讨论】:

    • 我明白了:> Traceback(最近一次调用最后一次)() 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 """从给定事件中删除回调。""" ---> 64 self.callbacks[event].remove(function) 65 66 def trigger(self, event, *args, **kwargs): ValueError: list.remove(x): x 不在列表中
    • 当您覆盖 plotly 的 API 时,它会变得优雅,当检测到在 colab 运行时 (get_ipython().__class__.__module__ == "google.colab._shell") 上运行时,您有条件地为 colab 进行初始化,否则不会。
    • 不应该是register打电话吗?
    【解决方案3】:

    您需要添加一个方法才能在 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

    【讨论】:

    • 这太棒了。尝试了所有其他解决方案后,这是唯一有效的解决方案。干得好,感谢您找到并发布它。
    【解决方案4】:

    您需要更改默认渲染。这是文档的摘录。 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']
    

    因此,解决问题的方法是指定默认渲染“colab”。

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

    【讨论】:

      【解决方案5】:

      只需将"colab" 作为fig.show(renderer="colab") 中参数renderer 的值传递

      例子:

      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 非常有效的解决方案
      • 此解决方案适用于 plotly 4.x 版
      猜你喜欢
      • 2021-02-17
      • 2019-05-30
      • 2019-02-04
      • 2021-12-12
      • 2023-03-23
      • 2016-09-02
      • 1970-01-01
      • 2023-03-31
      相关资源
      最近更新 更多