Plotly#

Plotly is a relatively new JavaScript based plotting library for Python and several other languages. It’s free and open source, but developed by Plotly Technology Inc providing commercial tools and services around Plotly. Plotly started as an online-only service (rendering done on a server), but now may be used offline without any data transfer to plotly.com.

Here we only cover 3d plots to have a good alternative to Matplotlib’s limited 3d capabilities. But plotly allows for 2d plotting, too. A major advantage of Plotly is, that interactive Plotly plots can easily be integrated into websites.

The Plotly python package may be installed via conda from Plotly’s channel:

conda install -c plotly plotly

Plotly integrates well with NumPy and Pandas.

import numpy as np
import pandas as pd

Plotly Express#

The Plotly express interface to Plotly provides commands for complex standard tasks:

import plotly.express as px

a = np.random.rand(100)
b = np.random.rand(100)
c = a * b
df = pd.DataFrame({'some_feature': a, 'another_feature': b, 'result': c})

fig = px.scatter_3d(df, x='some_feature', y='another_feature', z='result', color='result', size='result', width=800, height=600)

fig.show()

Graph Object Interface#

For more advanced usage Plotly provides the graph object interface. Here we first have to create a Figure object, which then is filled with content step by step.

import plotly.graph_objects as go

fig = go.Figure()
fig.layout.width = 800
fig.layout.height = 600

x, y = np.meshgrid(np.linspace(0, 1, 30), np.linspace(0, 1, 30))
z = x * y

fig.add_trace(
    go.Surface(x=x, y=y, z=z, colorscale='Jet')
)

u = x.reshape(-1)
v = y.reshape(-1)
w = z.reshape(-1) + 0.3 * (np.random.rand(z.size) - 0.5)

fig.add_trace(
    go.Scatter3d(
        x=u, y=v, z=w,
        marker={'size': 2, 'color': 'rgba(255,0,0,0.5)'},
        line={'width': 0, 'color': 'rgba(0,0,0,0)'},
        hoverinfo = 'none'
    )
)
        
fig.show()

Exporting Figures#

Plotly plots can easily be exported to HTML with Figure.write_html:

fig.write_html('fig.html', include_plotlyjs='directory', auto_open=False)

The include_plotlyjs='directory' tells Plotly that the exported HTML file finds the Plotly JavaScript Library in the HTML file’s directory (for offline use). To make this work download Plotly’s JS bundle from Plotly’s GitHub repository.

Defautl behavior is that the exported file is opened automatically after export. To prevent this, use auto_open=False.