Plotly is collaborative, makes beautiful interactive graphs with a URL for you, and stores your data and graphs together. This NB shows how to use Plotly to share plots from some awesome Python plotting libraries. The matplotlylib project is a collaboration with mpld3 and Jake Vanderplas. We've put together a User Guide that outlines the full extent of Plotly's APIs.

For best results, you can copy and paste this Notebook and key. Run $ pip install plotly inside a terminal then start up a Notebook. We'll also be using ggplot, seaborn, and prettyplotlib, which you can also all install form pip. Let's get started.

You'll want to have version 1.0.0. If not, run $ pip install plotly --upgrade in a terminal. Check out our User Guide for more details on where to get your key. Problems or questions? Email feedback@plot.ly or find us on Twitter.

In addition to matplotlib and Plotly's own Python API, You can also use Plotly's other APIs for MATLAB, R, Perl, Julia, and REST to write to graphs. That means you and I could edit the same graph with any language. We can even edit the graph and data from the GUI, so technical and non-technical teams can work together. And all the graphs go to your profile, like this: https://plot.ly/~IPython.Demo.

You control the privacy by setting world_readable to False or True, and can control your sharing.

fig1=plt.figure()# Make a legend for specific lines.importmatplotlib.pyplotaspltimportnumpyasnpt1=np.arange(0.0,2.0,0.1)t2=np.arange(0.0,2.0,0.01)# note that plot returns a list of lines. The "l1, = plot" usage# extracts the first element of the list into l1 using tuple# unpacking. So l1 is a Line2D instance, not a sequence of linesl1,=plt.plot(t2,np.exp(-t2))l2,l3=plt.plot(t2,np.sin(2*np.pi*t2),'--go',t1,np.log(1+t1),'.')l4,=plt.plot(t2,np.exp(-t2)*np.sin(2*np.pi*t2),'rs-.')plt.xlabel('time')plt.ylabel('volts')plt.title('Damped oscillation')plt.show()

Now, to convert it to a Plotly figure, this is all it takes:

In [6]:

py.iplot_mpl(fig1)

You can hover, zoom, and pan on the figure. You can also strip out the matplotlib styling, and use Plotly's default styling.

Here's where this gets special. You can get the data from any Plotly graph. That means you can re-plot the graph or part of it, or use your favorite Python tools to wrangle and analyze your data. Check out our getting started guide for a full background on these features.

Or you can get the figure makeup. Here, we're using 'IPython.Demo', which is the username and '3357' which is the figure number. You can use this command on Plotly graphs to interact with them from the console. You can access graphs via a URL. For example, for this plot, it's:

Now let's suppose we wanted to add a fit to the graph (see our fits post to learn more), and re-style it a bit. We can go into the web app, fork a copy, and edit the image in our GUI. No coding required.

We also keep the data and graph together. You can analyze it, share it, or add to other plots. You can append data to your plots, copy and paste, import, or upload data. Take-away: a Python user could make plots with an Excel user, ggplot2 Ploty package, and MATLAB user. That's collaboration.

In [13]:

Image(url='https://i.imgur.com/Mq490fb.png')

Out[13]:

I can now call that graph into the NB. I can keep the styling, re-use that styling on future graphs, and save styles from other graphs. And if I want to see the data for the fit or access the figure styling, I can run the same commands, but on the updated figure and data for this graph. I don't need to re-code it, and I can save and share this version.

In [14]:

tls.embed('MattSundquist','1307')

Plotly graphs are always interactive, and you can even stream data to the browser. You can also embed them in the browser with an iframe snippet.

So you can keep all your plots for your project, team, or personal work in one plce, you get a profile, like this: https://plot.ly/~jackp/.

In [21]:

Image(url='https://i.imgur.com/gUC4ajR.png')

Out[21]:

You can also plot with Plotly with pandas, NumPy, datetime, and more of your favorite Python tools. We've already imported numpy and matplotlib; here we've kept them in so you can simply copy and paste these examples into your own NB.

In [22]:

fig3=plt.figure()importnumpyasnpimportmatplotlib.pyplotasplt# make a little extra space between the subplotsplt.subplots_adjust(wspace=0.5)dt=0.01t=np.arange(0,30,dt)nse1=np.random.randn(len(t))# white noise 1nse2=np.random.randn(len(t))# white noise 2r=np.exp(-t/0.05)cnse1=np.convolve(nse1,r,mode='same')*dt# colored noise 1cnse2=np.convolve(nse2,r,mode='same')*dt# colored noise 2# two signals with a coherent part and a random parts1=0.01*np.sin(2*np.pi*10*t)+cnse1s2=0.01*np.sin(2*np.pi*10*t)+cnse2plt.subplot(211)plt.plot(t,s1,'b-',t,s2,'g-')plt.xlim(0,5)plt.xlabel('time')plt.ylabel('s1 and s2')plt.grid(True)plt.subplot(212)cxy,f=plt.csd(s1,s2,256,1./dt)plt.ylabel('CSD (db)')py.iplot_mpl(fig3)

fig5=plt.figure()from__future__importprint_function"""Edward Tufte uses this example from Anscombe to show 4 datasets of xand y that have the same mean, standard deviation, and regressionline, but which are qualitatively different.matplotlib fun for a rainy day"""frompylabimport*x=array([10,8,13,9,11,14,6,4,12,7,5])y1=array([8.04,6.95,7.58,8.81,8.33,9.96,7.24,4.26,10.84,4.82,5.68])y2=array([9.14,8.14,8.74,8.77,9.26,8.10,6.13,3.10,9.13,7.26,4.74])y3=array([7.46,6.77,12.74,7.11,7.81,8.84,6.08,5.39,8.15,6.42,5.73])x4=array([8,8,8,8,8,8,8,19,8,8,8])y4=array([6.58,5.76,7.71,8.84,8.47,7.04,5.25,12.50,5.56,7.91,6.89])deffit(x):return3+0.5*xxfit=array([amin(x),amax(x)])subplot(221)plot(x,y1,'ks',xfit,fit(xfit),'r-',lw=2)axis([2,20,2,14])setp(gca(),xticklabels=[],yticks=(4,8,12),xticks=(0,10,20))text(3,12,'I',fontsize=20)subplot(222)plot(x,y2,'ks',xfit,fit(xfit),'r-',lw=2)axis([2,20,2,14])setp(gca(),xticklabels=[],yticks=(4,8,12),yticklabels=[],xticks=(0,10,20))text(3,12,'II',fontsize=20)subplot(223)plot(x,y3,'ks',xfit,fit(xfit),'r-',lw=2)axis([2,20,2,14])text(3,12,'III',fontsize=20)setp(gca(),yticks=(4,8,12),xticks=(0,10,20))subplot(224)xfit=array([amin(x4),amax(x4)])plot(x4,y4,'ks',xfit,fit(xfit),'r-',lw=2)axis([2,20,2,14])setp(gca(),yticklabels=[],yticks=(4,8,12),xticks=(0,10,20))text(3,12,'IV',fontsize=20)#verify the statspairs=(x,y1),(x,y2),(x,y3),(x4,y4)forx,yinpairs:print('mean=%1.2f, std=%1.2f, r=%1.2f'%(mean(y),std(y),corrcoef(x,y)[0][1]))py.iplot_mpl(fig5,strip_style=True)

An exciting package by Greg Lamp and the team at ŷhat is ggplot for Python. You can draw figures with ggplot's wonderful syntax and share them with Plotly. You'll want to run $ pip install ggplot to get started.

The lovely gallery of examples from prettyplotlib, a matplotlib enhnacing library by Olga Botvinnik, is a fun one to make interactive. Here's a scatter; let us know if you make others. You'll note that not all elements of the styling come through. Head over to the homepage for documentation.

In [39]:

fig12=plt.figure()importprettyplotlibasppl# Set the random seed for consistencynp.random.seed(12)# Show the whole color rangeforiinrange(8):x=np.random.normal(loc=i,size=800)y=np.random.normal(loc=i,size=800)ax=ppl.scatter(x,y,label=str(i))ppl.legend(ax)ax.set_title('prettyplotlib `scatter`')ax.legend().set_visible(False)py.iplot_mpl(fig12)

And another prettyplotlib example.

In [40]:

fig13=plt.figure()importprettyplotlibasppl# Set the random seed for consistencynp.random.seed(12)# Show the whole color rangeforiinrange(8):y=np.random.normal(size=1000).cumsum()x=np.arange(1000)# Specify both x and yppl.plot(x,y,label=str(i),linewidth=0.75)py.iplot_mpl(fig13)

Another library we really dig is seaborn, a library to maximize aesthetics of matplotlib plots. It's by by Michael Waskom. You'll need to install it with $ pip install seaborn, and may need to import six, which you can do from pip. The styling isn't yet translated to Plotly, so we'll go to Plotly's default settings.

fig20=plt.figure()importmatplotlib.pyplotaspltimportnumpyasnpnum_plots=10# Have a look at the colormaps here and decide which one you'd like:# http://matplotlib.org/1.2.1/examples/pylab_examples/show_colormaps.htmlcolormap=plt.cm.gist_ncarplt.gca().set_color_cycle([colormap(i)foriinnp.linspace(0,0.9,num_plots)])# Plot several different functions...x=np.arange(10)labels=[]foriinrange(1,num_plots+1):plt.plot(x,i*x+5*i)labels.append(r'$y = %ix + %i$'%(i,5*i))py.iplot_mpl(fig20,strip_style=True)