昨天在做课件的时间发现plotly弄死都不能在jupyterlab中正确的显示,但在jupyter notebook中正常,一直报告类似的错误:

VM458:2 Uncaught ReferenceError: require is not defined
    at <anonymous>:2:17
    at t.attachWidget (vendors~main.479571ea0f6c7741ac01.js:2)
    at t.insertWidget (vendors~main.479571ea0f6c7741ac01.js:2)
    at C._insertOutput (vendors~main.479571ea0f6c7741ac01.js:2)
    at C.onModelChanged (vendors~main.479571ea0f6c7741ac01.js:2)
    at m (vendors~main.479571ea0f6c7741ac01.js:2)
    at Object.c [as emit] (vendors~main.479571ea0f6c7741ac01.js:2)
    at e.emit (vendors~main.479571ea0f6c7741ac01.js:2)
    at f._onListChanged (vendors~main.479571ea0f6c7741ac01.js:2)
    at m (vendors~main.479571ea0f6c7741ac01.js:2)

有多个issue提到了这个问题但试过了所有的方法还是无法解决:

最后看了下pio.renderers提供了多种渲染方式,试了下iframe能够解决问题。

Renderers configuration
-----------------------
    Default renderer: 'iframe'
    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', 'sphinx_gallery_png']

所以最终的解决方案是:

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