After exploring some options to enable interactive plot displays via Jupyter Notebooks in our Projects posts, I came across the Plotly API module. The following example demonstrates using Plotly to create an interactive figure within a notebook. Plotly is an external web-based service that uses D3.js, a popular JavaScript visualization library. After installing plotly locally with pip install plotly, I had to create an account online to get an API username and key, allowing Python to send my data to Plotly.

Here is an example from section 8 of Plotly's 3D plot tutorial

Mouse-over coordinates, zoom, and rotate in the resulting figure below!

In [1]:
# Import plotly package
import plotly

# Check plotly version
In [2]:
# To communicate with Plotly's server, sign in with credentials file
import plotly.plotly as py

# Useful Python/Plotly tools
import as tls

# Graph objects to piece together plots
from plotly.graph_objs import *

import numpy as np 
In [3]:
from numpy import pi, cos, exp

# Define the function to be plotted
def fxy(x, y):
    A = 1  # choose a maximum amplitude 
    return A*(cos(pi*x*y))**2 * exp(-(x**2+y**2)/2.)
In [4]:
# Choose length of square domain, make row and column vectors
L = 4
x = y = np.arange(-L/2., L/2., 0.1)  # use a mesh spacing of 0.1
yt = y[:, np.newaxis]  # make column vector

# Get surface coordinates!
z = fxy(x, yt)
In [5]:
trace1 = Surface(
    z=z,  # link the fxy 2d numpy array
    x=x,  # link 1d numpy array of x coords
    y=y   # link 1d numpy array of y coords

# Package the trace dictionary into a data object
data = Data([trace1])
In [6]:
# Dictionary of style options for all axes
axis = dict(
    showbackground=True, # (!) show axis background
    backgroundcolor="rgb(204, 204, 204)", # set background color to grey
    gridcolor="rgb(255, 255, 255)",       # set grid line color
    zerolinecolor="rgb(255, 255, 255)",   # set zero grid line color

# Make a layout object
layout = Layout(
    title='$f(x,y) = A \cos(\pi x y) e^{-(x^2+y^2)/2}$', # set plot title
    scene=Scene(  # (!) axes are part of a 'scene' in 3d plots
        xaxis=XAxis(axis), # set x-axis style
        yaxis=YAxis(axis), # set y-axis style
        zaxis=ZAxis(axis)  # set z-axis style
In [7]:
# Make a figure object
fig = Figure(data=data, layout=layout)

# Send to Plotly and show in notebook
py.iplot(fig, filename='s8_surface')
High five! You successfuly sent some data to your account on plotly. View your plot in your browser at or inside your account where it is named 's8_surface'