How To Create a Plotly Visualization And Embed It On Websites | by Elizabeth Ter Sahakyan | Towards Data Science

Plotly is an open-source, simple-to-use charting library for python. Plotly.express was built as a wrapper for Plotly.py to make creating interactive visualizations as easy as writing one line of python ✨
plotly.express is to plotly what seaborn is to matplotlib
There are so many cool interactive visualizations that can be created with Plotly Express — like this one using a dataset from Airbnb:
Interactive visualizations created with Plotly express can be rendered and displayed by most notebooks and IDE’s. Embedding them elsewhere is a different story. If you’ve been running into trouble with embedding your interactive plotly visualizations you’re in the right place!
In this article, I’ll go over how to create a basic interactive visualization with plotly express and generate the iframe embed code to display it on any website.
The steps are as follows:
create plotly visualization
host visualization (either on plotly or github pages)
get iframe embed code
If you haven’t already, install plotly into your environment using !pip install plotly and import plotly using import plotly.express as px.
Run the following code to create a basic visualization:
gapminder = px.data.gapminder()fig = px.scatter(gapminder.query("year==2007"), x="gdpPercap", y="lifeExp", size="pop", color="continent",           hover_name="country", log_x=True, size_max=60)fig.show()
The figure below should appear in your notebook:
Now that you have an interactive visualization to work with...let’s host it somewhere!
If your dataset is small enough you’ll be able to upload your visualization to plotly on a free account— and if it’s not, it’ll give you an error when you try the part below. I’ll explain in the next section how to get around it if you run into the error.
To upload the visualization to your plotly account, install chart studio using !pip install chart_studio and then import it using import chart_studio.
You’ll need your username and api key from your plotly account to connect to it from your notebook. To get your api key, just click your username in the top right corner of your profile and click settings, then regenerate a new api key. Now you can set your credentials:
username = '' # your usernameapi_key = '' # your api key - go to profile > settings > regenerate keychart_studio.tools.set_credentials_file(username=username, api_key=api_key)
Push your visualiztion to your account using the following lines of code:
import chart_studio.plotly as pypy.plot(fig, filename = 'gdp_per_cap', auto_open=True)
If done correctly, this code should open a new window with your visualization on your account and return the link in your notebook. You can use that same link to then embed on websites that support embedding with embed.ly, like Medium. Note: while you’re drafting a post on Medium your visualization will not be interactive, but once you publish it it will work.
Here is the interactive visualization we created that I embedded in Medium just by pasting the link ...easy.
If uploading your visualization to plotly worked for you — great. You can skip over to the next section where I’ll show you how to generate the iframe embed code.
When the dataset you’re working with is too big, you will get an error from plotly that you can’t upload the visualization unless you upgrade your account. So to get around this we are going to write our plotly visualization to HTML.
First, let’s create a visualization with a large data set. I’m going to use data from Airbnb, which can be found in this github repo. You can download the csv if you want to follow along.
Below is the code to create the dataframe that I’ll be using:
And here is the code to create the visualization:
fig = px.scatter(df, x='Neighborhood', y='Price (US Dollars)'                 ,size='Accommodates'                 , hover_data=['Bedrooms', 'Wifi', 'Cable TV', 'Kitchen', 'Washer', 'Number of Reviews']                 ,color= 'Room Type')fig.update_layout(template='plotly_white')fig.update_layout(title='How much should you charge in a Berlin neighborhood?')fig.show()
The output will look like this:
And now if you try uploading this to your plotly account using py.plot(fig, filename='airbnb', auto_open=True), you will get this error:
PlotlyRequestError: This file is too big! Your current subscription is limited to 524.288 KB uploads. For more information, please visit: https://go.plot.ly/get-pricing.
So instead, we’re going to write our visualization to HTML and host it on github pages.
To generate the HTML file for the plotly visualization, use:
import plotly.io as piopio.write_html(fig, file=’index.html’, auto_open=True)
If done correctly, this code will open up the local HTML file in your browser and you should see the visualization.
Publishing to github pages is super simple. You can follow the instructions documented by github here or follow my brief overview.
Create a new github repo and initialize with a README.md. Upload the index.html file we just created and commit it to the master branch. Now, click settings, and scroll down to the github pages section and under ‘Source’ select ‘master branch’ .
You should now be able to view your visualization using this link structure http://username.github.io/repository
And the one I just made can be found here https://elizabethts.github.io/publish-plotly-website/.
Now that we have the link to our plotly visualization (either hosted on plotly or github pages) we can generate an iframe code for the visualization. If you were able to upload your visualization to plotly, generating the iframe embed code can be done with this line of code:
import chart_studio.tools as tlstls.get_embed('https://plot.ly/~elizabethts/9/') #change to your url
This will give you the output:
<iframe id="igraph" scrolling="no" style="border:none;" seamless="seamless" src="https://plot.ly/~elizabethts/9.embed" height="525" width="100%"></iframe>
If you went the github pages route, you will need to modify the iframe code above yourself. Just replace the plotly url with the github url!
Finally, you can place this iframe embed code into your site and your visualization will appear! Note: you might have to modify the height and width if you are using the github link.
Ironically, you can’t embed your interactive visualization on Medium if your dataset was too large and you had to host it on github, that I know of. To get around this, I highly recommend using CloudApp to screen record gifs that you can easily drag and drop into your Medium article, which is what I did in this one.
And there you go — you can now create an interactive plotly visualization and generate the iframe embed code to display it on any website!
Find me on twitter @elizabethets!