如何保存 Plotly 文件并从 DBFS 进行显示How to save Plotly files and display From DBFS

可以将使用 Plotly 生成的图表作为 jpgpng 文件保存到驱动程序节点。You can save a chart generated with Plotly to the driver node as a jpg or png file. 然后,可以使用 displayHTML() 方法在笔记本中显示它。Then, you can display it in a notebook by using the displayHTML() method. 默认情况下,会将 Plotly 图表保存到群集中驱动程序节点上的 /databricks/driver/ 目录。By default, you save Plotly charts to the /databricks/driver/ directory on the driver node in your cluster. 以后使用以下过程显示该图表。Use the following procedure to display the charts at a later time.

  1. 生成示例绘图:Generate a sample plot:

    data = {'data': [{'y': [4, 2, 3, 4]}],
                'layout': {'title': 'Test Plot',
                           'font': dict(size=16)}}
    p = plot(data,output_type='div')
    displayHTML(p)
    

    no-alternative-textno-alternative-text

  2. 使用 plotly.io.write_image() 将生成的绘图保存到文件中:Save the generated plot to a file with plotly.io.write_image():

    plotly.io.write_image(fig=data,file="/databricks/driver/plotly_images/<imageName>.jpg", format="jpeg",scale=None, width=None, height=None)
    
  3. 从驱动程序节点复制文件并将其保存到 DBFS:Copy the file from the driver node and save it to DBFS:

    dbutils.fs.cp("file:/databricks/driver/plotly_images/<imageName>.jpg", "dbfs:/FileStore/<your_folder_name>/<imageName>.jpg")
    
  4. 使用 displayHTML() 显示图像:Display the image using displayHTML():

    displayHTML('''<img src="/files/<your_folder_name>/<imageName>.jpg">''')
    

另请参阅 Python 和 R 笔记本中的 PlotlySee also Plotly in Python and R Notebooks.