I am trying to render charts using Plotly library in Databricks. However, no image is rendered. I use for example this statement:

from plotly.offline import init_notebook_mode, iplotfrom plotly import graph_objs as go# Initialize plotlyinit_notebook_mode(connected=True)daily_df=dfdef 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)

There is no output. Why?

3

Best Answer


If you use plotly version 4.2, you no longer need to import plotly.offline and you can just call fig.show() on your figure created with Plotly Express or go.Figure(). The new renderer framework has a Databricks-specific renderer :)

Full documentation here: https://plot.ly/python/renderers/ and https://plot.ly/python/creating-and-updating-figures/

Expanding on @nicolaskruchten answer,
Make sure your default renderer is set to:

pio.renderers.default = 'databricks'

-or-

Declare renderer as you show figure:

fig.show(renderer='databricks')

Edit: Plotly has updated its library to support better rendering in Databricks. See the answer above.

From looking at the docs, you have to specify output_type='div' and pass the plot object to displayHTML(). Here's a working example in a Python notebook or cell:

## Install & import plotly!pip install plotlyfrom plotly.offline import plotimport plotly.graph_objs as goimport numpy as npx = 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)