Search code examples
python-3.xmatplotlibplotlydatabricks

How to render charts in Databricks using Plotly?


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, 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)

There is no output. Why?


Solution

  • 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 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)