如何使用 Plotly 在 Databricks 中呈现图表?

How to render charts in Databricks using Plotly?

我正在尝试使用 Databricks 中的 Plotly 库呈现图表。但是,没有渲染图像。我使用例如这个语句:

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

    # Initialize plotly
    init_notebook_mode(connected=True)

    daily_df=df

    def plotly_df(df, title=''):
        """Visualize all the dataframe columns as line plots."""
        common_kw = dict(x=df.index, mode='lines')
        data = [go.Scatter(y=df[c], name=c, **common_kw) for c in df.columns]
        layout = dict(title=title)
        fig = dict(data=data, layout=layout)
        iplot(fig, show_link=False)

    plotly_df(daily_df)

没有输出。为什么?

如果您使用 plotly 4.2 版,则不再需要 import plotly.offline,您只需在使用 Plotly Express 或 go.Figure() 创建的图形上调用 fig.show()。新的渲染器框架有一个特定于 Databricks 的渲染器:)

完整文档在这里:https://plot.ly/python/renderers/ and https://plot.ly/python/creating-and-updating-figures/

编辑:Plotly 已更新其库以支持更好地在 Databricks 中呈现。见上面的答案。

从查看 the docs 开始,您必须指定 output_type='div' 并将绘图对象传递给 displayHTML()。这是 Python 笔记本或单元格中的一个工作示例:

## Install & import plotly
!pip install plotly
from plotly.offline import plot
import plotly.graph_objs as go
import numpy as np

x = np.random.randn(2000)
y = np.random.randn(2000)

# Instead of simply calling plot(...), store your plot as a variable and pass it to displayHTML().
# Make sure to specify output_type='div' as a keyword argument.
# (Note that if you call displayHTML() multiple times in the same cell, only the last will take effect.)

p = plot(
  [
    go.Histogram2dContour(x=x, y=y, contours=dict(coloring='heatmap')),
    go.Scatter(x=x, y=y, mode='markers', marker=dict(color='white', size=3, opacity=0.3))
  ],
  output_type='div'
)

displayHTML(p)