How To Create a Plotly Visualization And Embed It On Websites

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

Creating a Plotly Visualization

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!

Uploading A Visualization to Plotly

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 username
api_key = '' # your api key - go to profile > settings > regenerate key

chart_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 py
py.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.

Generating HTML for Plotly Visualizations

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:

import pandas as pd
df = pd.read_csv('airbnb.csv') # path to  csv

def clean_data(df):
    
    # replace numbers with strings
    df.neighborhood = df.neighborhood.map({1 : 'Friedrichshain-Kreuzberg', 2 : 'Mitte', 3 : 'Pankow', 4 : 'Neukölln', 5 :'Charlottenburg-Wilm',
                        6 : 'Tempelhof - Schöneberg', 7 : 'Lichtenberg', 8 : 'Treptow - Köpenick', 9 : 'Steglitz - Zehlendorf',
                        10 : 'Reinickendorf', 11 : 'Marzahn - Hellersdorf', 12 : 'Spandau'})

    df.room_type = df.room_type.map({1 : 'Entire home/apt', 2 : 'Private room', 3 : 'Shared room'})

    yes_no_dict = {0: 'No', 1:'Yes'}
    df.wifi = df.wifi.map(yes_no_dict)
    df.washer = df.washer.map(yes_no_dict)
    df.cable_tv = df.cable_tv.map(yes_no_dict)
    df.kitchen = df.kitchen.map(yes_no_dict)
    
    # rename columns
    df.rename(columns={'neighborhood': 'Neighborhood', 'room_type': 'Room Type', 'accommodates': 'Accommodates',
                      'bedrooms': 'Bedrooms', 'number_of_reviews': 'Number of Reviews', 'wifi': 'Wifi', 'cable_tv': 'Cable TV',
                      'washer': 'Washer', 'kitchen': 'Kitchen', 'price': 'Price (US Dollars)'}, inplace=True)
    
    # remove outliers
    df = df[df['Price (US Dollars)']<501]
    
    return df

# clean data
df = clean_data(df)

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.

Create HTML

To generate the HTML file for the plotly visualization, use:

import plotly.io as pio
pio.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.

Host to GitHub Pages

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/.

Embed A Plotly Visualization with iframe

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 tls
tls.get_embed('https://plot.ly/~elizabethts/9/') #change to your url

This will give you the output:

https://plot.ly/~elizabethts/9.embed

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 or LinkedIn!

Sources:

plotly
Plotly’s Python graphing library makes interactive, publication-quality graphs. Examples of how to make line plots…plot.ly

Getting Started with Plotly for Python
Plot can be set to three different type of privacies: public, private or secret. public: Anyone can view this graph. It…plot.ly

✨ Introducing Plotly Express ✨
Plotly Express is a new high-level Python visualization library: it’s wrapper for Plotly.py that exposes a simple…medium.com

Embedding Graphs in HTML
Plotly graphs can be embedded in any HTML page. This includes IPython notebooks, WordPress sites, dashboards, blogs…plot.ly

GitHub Pages
Grab your favorite text editor and add an index.html file to your project: Hello World I’m hosted with GitHub Pages…pages.github.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s