- Tue 09 October 2018
- datascience
- #plotly
When I initially started using Plotly, I had problems getting my visualizations to show up on my blog. I'm making this post to demonstrate how to use plotly visualizations in Jupyter Notebooks as well as how to embed them into websites. I also have a few cool tips for Jupyter Notebook.
Import Libraries¶
import pandas as pd
import numpy as np
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
import cufflinks as cf
init_notebook_mode(connected=True)
cf.go_offline()
#example dataset
df1 = pd.DataFrame(np.random.randn(200,5),columns='A B C D E'.split())
df1.head()
The code below normally allows the user to display Plotly visualizations in Jupyter Notebook, but the issue is that this does not display on a static web page. This is problematic because people usually like to see visualizations and not a blank box.
#scatter plot
df1.iplot(kind='scatter',x='A',y='B',mode='markers',size=10, title='Scatter Plot')
I fix this problem by exporting my plot to plot.ly (you will see a button in the bottom right corner of your graph) and embedding the plot as shown below:
import plotly.tools as tls
tls.embed('https://plot.ly/~ruer98/3/') #embeds plot in notebook
#boxplot
#df1.iplot(kind='box')
tls.embed('https://plot.ly/~ruer98/5/')
#spread plot
#df1[['A','B']].iplot(kind='spread')
tls.embed('https://plot.ly/~ruer98/7/')
#histogram
#df1['C'].iplot(kind='hist',bins=50)
tls.embed('https://plot.ly/~ruer98/9/')
#bubble plot
#df1.iplot(kind='bubble',x='C',y='D',size='E')
tls.embed('https://plot.ly/~ruer98/11/')
#scatter matrix
#this is basically an interactive version of sns.pairplot()
#df1.scatter_matrix()
tls.embed('https://plot.ly/~ruer98/13/')
#more example data
df2 = pd.DataFrame({'Category':'A B C'.split(),'Values':[46,37,52]})
df2.head()
#bar plot
#df2.iplot(kind='bar',x='Category',y='Values',xTitle='Category',yTitle='Values',title='Bar Plot')
tls.embed('https://plot.ly/~ruer98/15/')
#even more example data
df3 = pd.DataFrame({'x':[1,2,3,4,5],'y':[10,20,30,20,10],'z':[5,4,3,2,1]})
df3.head()
#surface plot
#df3.iplot(kind='surface', colorscale='rdylgn')
tls.embed('https://plot.ly/~ruer98/17/')
That was a brief overview of the powerful plotting that Plotly is capable of. Here is a few cool things you can do with...
Ipython.display¶
display math formulas in your notebook using Latex:
from IPython.display import display, Math, Latex
display(Math(r'F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx'))
embed HTML and IFrame content:
from IPython.display import IFrame, HTML
IFrame(src='https://s3.amazonaws.com/duhaime/blog/visualizations/isolation-forests.html', width=700, height=600)
or even embed a Youtube video:
from IPython.display import YouTubeVideo
YouTubeVideo("wupToqz1e2g")
I hope this post was enjoyable and informative. As always I encourage any comments, questions, and suggestions that you may have.