The Plotly Python API allows you to use familiar matplotlib syntax and make shareable, interactive, web-based Plotly graphs. All you do is add fig_to_plotly. You can install matplotlylib to get started plotting with imports, lines plots, subplots, annotations, bar charts, and scatters. Matplotlylib was inspired by and is part of the mpld3 project, headed by Jake Vanderplas.
Below are examples adapted from the matplotlib gallery and some of our favorite IPython NBs from the IPython gallery of interesting Notebooks. Check out the NBs for the original graphs and the full context. If you have feedback, questions, or suggestions, let us know at feedback@plot.ly or @plotlygraphs. Happy plotting!
%pylab inline
import matplotlib.pyplot as plt # side-stepping mpl backend
import matplotlib.gridspec as gridspec # subplots
import numpy as np
Populating the interactive namespace from numpy and matplotlib
You can use this key and username to run these examples. Sign up for an account. It's free, online, and you own your data. Public sharing is free. It's like GitHub, but for graphs and data.
from matplotlylib import fig_to_plotly
username = 'IPython.Demo'
api_key = '1fw3zw2o13'
We'll start with a few a examples from the matplotlib gallery. First up is a subplots example. The figure is re-drawn as an interactive graph in Plotly. You can click through to the "data and graph" link, and edit the graph with others from the GUI. Since we also have MATLAB and R APIs, that means you can plot with others in your languages of choice, or from the GUI, and edit the same graph.
You can also share your data and graphs and edit it with others, export your data and graph, and embed it in an iframe. You control whether it's private or public.
fig1 = plt.figure()
x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)
plt.subplot(2, 1, 1)
plt.plot(x1, y1, 'yo-')
plt.title('A tale of 2 subplots')
plt.ylabel('Damped oscillation')
plt.subplot(2, 1, 2)
plt.plot(x2, y2, 'r.-')
plt.xlabel('time (s)')
plt.ylabel('Undamped')
plt.show()
fig_to_plotly(fig1, username, api_key, notebook= True)
You'll notice there are a few slight differences, like ticks and spacing. We're continuing to work on the exporter, so please let us know or open an issue on our GitHub repo if you find something you'd like changed. You can edit, save, and share your plots with code or from the GUI.
Next up we'll draw this scatter plot. To keep the NB shorter, we won't show the mpl figure with each call.
fig2 = plt.figure()
N = 50
x = np.random.rand(N)
y = np.random.rand(N)
area = np.pi * (15 * np.random.rand(N))**2 # 0 to 15 point radiuses
plt.scatter(x, y, s=area, alpha=0.5)
fig_to_plotly(fig2, username, api_key, notebook= True)
Next up, a plot with a few annotations and text labels showing how LaTeX looks in Plotly.
fig3 = plt.figure()
font = {'family' : 'serif',
'color' : 'darkred',
'weight' : 'normal',
'size' : 16,
}
x = np.linspace(0.0, 5.0, 100)
y = np.cos(2 * np.pi * x) * np.exp(-x)
plt.plot(x, y, 'k')
plt.title('Damped exponential decay', fontdict=font)
plt.text(2, 0.65, r'$\cos(2 \pi t) \exp(-t)$', fontdict=font)
plt.xlabel('time (s)', fontdict=font)
plt.ylabel('voltage (mV)', fontdict=font)
# Tweak spacing to prevent clipping of ylabel
plt.subplots_adjust(left=0.15)
fig_to_plotly(fig3, username, api_key, notebook= True)
This lovely figure come from a tutorial on "matplotlib - 2D and 3D plotting in Python" by J.R. Johansson. Note that you can set the trace and marker styling.
x = linspace(0, 5, 10)
y = x ** 2
fig4 = plt.figure()
subplot(1,2,1)
plot(x, y, 'r--')
subplot(1,2,2)
plot(y, x, 'g*-');
fig_to_plotly(fig4, username, api_key, notebook= True)
Plotly also lets you draw subplots, and make figures with multiple axes (though you'll want to use our native syntax for that).
Full credit for the delightful plots that follow goes to Rick Muller and comes from his Crash course in Python. For fun, if you run your mouse over this first one, you'll notice the hover text changes color. You can also click and drag over a section of the grid to zoom in. Love it.
fig5 = plt.figure()
npts = 5000
xs = 2*rand(npts)-1
ys = 2*rand(npts)-1
r = xs**2+ys**2
ninside = (r<1).sum()
figsize(6,6) # make the figure square
title("Approximation to pi = %f" % (4*ninside/float(npts)))
plot(xs[r<1],ys[r<1],'b.')
plot(xs[r>1],ys[r>1],'r.')
figsize(8,6) # change the figsize back to 4x3 for the rest of the notebook
fig_to_plotly(fig5, username, api_key, notebook= True)
And another plot from the Crash Course shows a slick a stacked subplot.
fig6 = plt.figure()
from scipy.fftpack import fft,fftfreq
npts = 4000
nplot = npts/10
t = linspace(0,120,npts)
def acc(t): return 10*sin(2*pi*2.0*t) + 5*sin(2*pi*8.0*t) + 2*rand(npts)
signal = acc(t)
FFT = abs(fft(signal))
freqs = fftfreq(npts, t[1]-t[0])
subplot(211)
plot(t[:nplot], signal[:nplot])
subplot(212)
plot(freqs,20*log10(FFT),',')
fig_to_plotly(fig6, username, api_key, notebook = True)
This plot come from a NB on the "First few lectures of the UW/Coursera course on Data Analysis", by Chris Fonnesbeck. Chris has also done a cool NB on Titanic passengers, coal mining disasters, and vessel speed changes.
Since Plotly is free and online, we hope it could be useful for professors and students crafting plots, learning, and sharing their work. If you have ideas or would like to collaborate, please let us know!
import scipy as sp
from numpy.fft import *
L = 20
n = 128
x = linspace(-L/2., L/2., n, endpoint=False)
fig7 = plt.figure()
u = exp(-x**2)
plot(x,u)
fig_to_plotly(fig7, username, api_key, notebook = True)
These next two figures come from a beautiful NB that walks through how to use matplotlib and Mayavi to visualize complex-valued functions.
from matplotlib.colors import hsv_to_rgb
rcdef = plt.rcParams.copy()
def g(x):
return (1.0-1/(1+x**2))**0.2
fig8 = plt.figure()
plt.rcParams.update(rcdef)# reset plt.rcParams to default
x=np.linspace(0,10, 1000)
y=g(x)
f=lambda z: (1.0-1.0/(1+z**2))**0.5
h=lambda z: (1.0-1.0/(1+z**2))**0.4
plt.plot(x,y)
plt.plot(x, f(x), 'r')
plt.plot(x, h(x), 'g')
fig_to_plotly(fig8, username, api_key, notebook = True)
fig9 = plt.figure()
X=np.linspace(0,8,800)
Y=X-np.floor(X)
plt.rcParams['figure.figsize'] = 5, 3
plt.title('The graph of fract(x)')
plt.plot(X,Y,'r')
fig_to_plotly(fig9, username, api_key, notebook = True)