A short tutorial on Plotly in Python (2023)

My experience with Plotly in Python - simple steps to create beautiful, interactive data visualizations.
Author
Affiliation
Sid Metcalfe

Cartesian Mathematics Foundation

Published

December 1, 2023

Introduction

I started using Plotly for my data visualization projects and it has been a game changer. It’s one of those tools that once you start using, you wonder how you managed without it. The ability to turn complex data into interactive charts with minimal fuss has not just made my analysis clearer, but also more engaging for anyone who sees it. Whether you’re new to data plotting or looking to switch up your current toolkit, my experience with Plotly might just convince you to give it a try. Here’s how I got started and why I think it’s worth considering for your next data visualization task.

Introduction to Plotly and Installation

Plotly is a game changer for anyone diving into data visualization in Python. It’s versatile, it’s interactive, and it’s ridiculously easy to pick up, even if you’re new to plotting data. My first encounter with this library turned my graphs from bland to brilliant with just a few lines of code.

Installation is a breeze. You need to have Python already installed on your system; if you haven’t, hit up python.org and follow their straightforward instructions. With Python ready, pop open your terminal or command prompt and enter:

pip install plotly

That’s it! This command fetches the latest version of Plotly from PyPI and installs it. If you’re using Jupyter notebook or JupyterLab for your projects, consider installing the “notebook” and “ipywidgets” packages for a fully interactive experience:

pip install "notebook>=5.3" "ipywidgets>=7.2"

Now, let’s verify that the installation went as planned. I always like to test my library installs to avoid hiccups down the line. Launch your Python interactive shell or your favorite IDE, and type:

import plotly
print(plotly.__version__)
5.11.0

You should see the version number of Plotly printed out. No errors? Perfect, let’s forge ahead.

One of my favorite things about Plotly is that it’s compatible with Pandas. If you’re like me and you use Pandas dataframes as your data analysis Swiss Army knife, you’re in luck. Plotly plays nice with them, which means creating plots directly from your dataframes is a piece of cake.

Here’s how you would import Plotly into your script along with Pandas:

import plotly.express as px
import pandas as pd

Plotly Express, often imported as “px”, is the streamlined syntax for creating figures. It packs a lot of power into a few lines of code. For those interested in expanding their data analysis skills with Python, consider checking out A short step-by-step introduction to NumPy (2024). Now, to prove how straightforward this all is, here’s a sample snippet that uses Plotly to plot a simple scatter plot from a Pandas dataframe:

# Sample dataframe
d = {'x': [1, 2, 3, 4], 'y': [10, 11, 12, 13]}
df = pd.DataFrame(data=d)

# Create a simple scatter plot
fig = px.scatter(df, x='x', y='y', title='Simple Scatter Plot with Plotly')
fig.show()

The figure object, “fig” in this case, represents the actual graph. You can manipulate it, add titles, tweak axis labels, and when you’re ready to see your creation, fig.show() flings it onto your screen.

What you’ll get is not just any graphic; it’s interactive out-of-the-box. Hover your mouse over the data points and see the coordinates pop up. Click and drag to zoom. It’s not static; you’ll want to play with your data.

This is just the tip of the iceberg, and I’m excited for you to see what else you can do. In the following sections of this tutorial, I’ll walk you through creating your first plot, customizing graphs, and making the most of Plotly’s interactive features. Once you get the hang of it, brace yourself—you might not want to go back to static plots ever again.

Creating Your First Plot with Plotly

When I started with Plotly, one of the first things I appreciated was its straightforward approach to creating plots. The simplicity coupled with the power to generate sophisticated visualizations intrigued me. Plotly, if you’re not yet familiar, is a graphing library that makes it simple to create interactive, publication-quality graphs online.

I’ll walk you through creating a basic line chart, which is usually the starting point for most people learning data visualization. Let’s consider a scenario where we’ve got some temperature data over a week, and we’d like to plot this to discern patterns more easily.

First things first, we need to have Plotly installed, which I assume you’ve got covered from the earlier sections of the tutorial. Now, open up your favorite code editor or an interactive Python environment, and let’s jump right into the code.

import plotly.graph_objs as go
import plotly.io as pio

# Sample data: average daily temperatures over a week
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
temperatures = [22, 24, 21, 23, 25, 27, 22]

# Create the plot
fig = go.Figure(data=go.Scatter(x=days, y=temperatures, mode='lines+markers'))

# Make it visually appealing
fig.update_layout(
title='Weekly Temperature Overview',
xaxis_title='Day of the Week',
yaxis_title='Temperature (Celsius)'
)

# Show the plot
fig.show()

This small chunk of code will produce a clean, interactive line chart. Let’s break down what’s happening here:

  1. We’re importing the necessary modules from Plotly.
  2. We’ve got our x (days) and y (temperatures) data defined in simple lists.
  3. We’re constructing the plot using go.Figure and adding a scatter plot (which in Plotly, is used for both scatter and line charts) layer through go.Scatter.
  4. We’re using mode='lines+markers' to denote that we want both lines and markers on our scatter plot.
  5. Inside update_layout, we’re adding a title and axis labels, which are always good practice for clarity.
  6. Finally, fig.show() renders the chart in a web browser.

I remember the first time I rendered a plot using Plotly. Seeing the interactive chart popup was pretty satisfying—it felt like my data had suddenly come to life. You can hover over points, zoom in, and pan across the plot easily. These features are built-in with no extra effort on your part, providing a professional-looking plot with minimal code.

What’s nice about Plotly is that it seamlessly fits into the data science workflow, especially when coupled with libraries like Pandas. If you’re working with a DataFrame, you can plot your data directly using Plotly, given that it integrates well with Pandas.

import plotly.express as px
import pandas as pd

# Let's say you've got a DataFrame created from some dataset
df = pd.DataFrame({
'days': days,
'temperatures': temperatures
})

# Now, use Plotly Express to create the same plot
fig = px.line(df, x='days', y='temperatures', title='Weekly Temperature Overview')
fig.show()

Using plotly.express, which is a high-level interface for Plotly, makes the code even more concise. You directly pass your DataFrame to px.line, specify the column names for your x and y axes, and you’re done. Easy, right?

Remember, don’t stress about memorizing these instructions or getting everything perfect from the get-go. The beauty of programming is in trial and error, running code and seeing what comes out on the other side. Each chart you build is a step towards mastering Plotly and data visualization in Python.

Customizing Graphs in Plotly

Plotly graphs are far from static; they can be as dynamic and complex as you need them to be. When I first began customizing graphs in Plotly, the breadth of options was daunting, but I quickly realized the power of this tool to create communicative and aesthetically compelling visualizations.

Let’s say you want to customize the basic line graph. It starts with the data:

import plotly.graph_objs as go

# Sample data
x_data = [1, 2, 3, 4]
y_data = [10, 11, 12, 13]

# Create the Plotly graph object
fig = go.Figure(data=go.Scatter(x=x_data, y=y_data))

What you have here is a no-frills line graph. But let’s say the default aesthetics aren’t quite what you’re looking for. This is where customization comes in.

To change the line style, you can tweak the Scatter object:

fig = go.Figure(data=go.Scatter(x=x_data, y=y_data, mode='lines+markers', line=dict(color='firebrick', width=4, dash='dashdot')))

Just with this, you’ve already added markers to the line graph, changed the color to a shade of red, increased the line width, and applied a dash-dot pattern. But what about the rest of the chart? The background, gridlines, and axes could use some love too.

Customizing the layout is another powerful feature that allows you to modify nearly anything:

fig.update_layout(
title='Customized Line Graph',
xaxis_title='X Axis Title',
yaxis_title='Y Axis Title',
paper_bgcolor='rgba(233,233,233,1)',
plot_bgcolor='rgba(233,233,233,1)',
xaxis=dict(
showline=True,
showgrid=False,
showticklabels=True,
linecolor='rgb(204, 204, 204)',
linewidth=2,
ticks='outside',
tickfont=dict(
family='Arial',
size=12,
color='rgb(82, 82, 82)'),
),
yaxis=dict(
showgrid=True,
zeroline=False,
showline=True,
showticklabels=True,
)
)

With update_layout, I set the chart title, axis titles, and modified the background color. I also adjusted the x-axis line color, tick labels, and gridlines – the little details that can make your chart easier to read and more visually pleasing.

An important resource I find incredibly useful is Plotly’s official documentation (https://plotly.com/python/). It’s detailed and full of examples. When I come across problems or want to learn new tricks, this is where I get most of my information.

To make your graph interactive, adding a hover effect is quite straightforward:

fig.update_traces(hoverinfo='text+name', mode='lines+markers')

Here, this command adds a hover effect that displays text and the trace name when you hover over a data point.

Lastly, you often want to save and share your creations:

fig.write_html('my_graph.html')

This simple line of code exports your fully interactive graph to an HTML file, which you can then embed in a website or share as is.

Customizing graphs in Plotly comes down to understanding what elements you can control and knowing how to modify them to suit your needs. The syntax is generally intuitive, which allows for quick learning by doing. The key is experimentation. Try changing various attributes and see how they affect the final outcome. The beauty of Plotly is that you see your changes in real-time, making the learning process very reinforcing.

Interactive Features of Plotly

Plotly excels at making interactive charts. Here’s a crash course on spicing up your visualizations.

First, the hover feature. By default, Plotly gives you a tooltip when you hover over points on your graph. Crucial info like the precise value of a data point gets displayed without cluttering your plot. Let’s see it in action.

import plotly.express as px

data = px.data.iris()  # Let's use the classic Iris dataset
fig = px.scatter(data, x='sepal_width', y='sepal_length', color='species')
fig.show()

When you run this, move your mouse over the dots. You’ll see the magic happen—a small box with details of the sepal dimensions. And color-coding by species adds that extra clarity.

Next, let’s enable zooming and panning. It’s effortless because Plotly has it baked in. You can zoom in on a particular region of your plot by drawing a box around it, or zoom out to see the bigger picture. Just use your scroll wheel or the plus and minus buttons. And if you get lost? Click the home button to reset.

In some cases, linking your charts can be enlightening. Imagine having two graphs side by side—zooming in on one would zoom in on the other accordingly. Check this out:

from plotly.subplots import make_subplots

fig = make_subplots(rows=1, cols=2)
fig.add_trace(
px.scatter(data, x='sepal_width', y='sepal_length').data[0],
row=1, col=1
)
fig.add_trace(
px.scatter(data, x='petal_width', y='petal_length').data[0],
row=1, col=2
)

fig.update_layout(hovermode='x unified')
fig.show()

Imagine you have these side-by-side plots on different attributes of the same dataset. Hover over a point on the left plot; the corresponding point on the right plot also hovers, connecting the two visually. This unified hovermode is incredibly handy for cross-referencing.

Animations are another cool aspect of Plotly. They work by updating the chart with new data points, giving the impression of motion over time. This could be great for representing trends or changes in data over intervals. Let’s make our static Iris scatter plot twirl with some animation.

fig = px.scatter(data, x='sepal_width', y='sepal_length',
animation_frame='petal_length', color='species')
fig.show()

With animation_frame, we’re essentially slicing our data along the ‘petal_length’ and watching how the remaining dimensions change with it. Slide through the frames, and watch the plot morph before your eyes.

But your interactivity doesn’t have to stop at what’s pre-made. For those who code, using Dash (by Plotly for creating web applications) is the next level. You can transform plots into interactive dashboards with sliders, buttons, and dropdowns to manipulate what’s visualized. Just a heads up: coding with Dash involves a steeper learning curve and a bit more setup. It’s well worth the effort if you’re serious about data visualization.

Interactive features elevate your data storytelling. They allow you to zoom in on specifics, provide broad overviews, compare side by side, and even animate changes over time. It’s like giving your audience a set of controls to explore the story you’re telling with your data. Try these features out. I hope this quick guide sparks ideas for your next data visualization project.

Sharing and Exporting Plotly Charts

Now that you’ve created your exquisite Plotly charts, let’s turn our attention to sharing and exporting them. There’s no point in keeping your masterful visualizations to yourself! Plotly makes it incredibly easy to share your charts with the world or with specific collaborators. Additionally, exporting your charts for use in reports, presentations, or any other medium is a breeze.

Starting with sharing, Plotly’s online platform called Chart Studio is a powerhouse. Initially, I was slightly intimidated by the thought of sharing my charts online, but it turned out to be incredibly straightforward. First things first, you need to have a Plotly account. Once you’ve got that sorted, here’s a snippet of code that will push your chart to the Plotly cloud:

import plotly.graph_objs as go
import plotly.io as pio

# Assuming you've created a figure object named 'fig'
fig = go.Figure(data=go.Bar(y=[2, 3, 1]))

# Set up your username and API key
pio.write_html(fig, file='index.html', auto_open=True)

# Alternatively, you can use Plotly's python library to upload your plot:
import chart_studio
import chart_studio.plotly as py

username = 'your_username'  # Replace with your own username
api_key = 'your_api_key'    # Replace with your API key

chart_studio.tools.set_credentials_file(username=username, api_key=api_key)
py.plot(fig, filename = 'my_bar_chart', auto_open=True)

When you use py.plot(), the chart will be rendered in your web browser, and it will also be saved to your account in Chart Studio, where you can share it with a link or embed it on your website.

But maybe you’re not interested in putting your charts online; perhaps you need them in your PowerPoint for that big presentation next week. No problem! Plotly makes exporting to different formats really simple, whether it is a static image like a PNG or JPEG, vector formats like SVG or PDF, or even to HTML. Here’s how you can export a static image:

fig.write_image("path/to/your/directory/your_chart_name.png")

And, if you prefer to work with an interactive HTML file:

fig.write_html("path/to/your/directory/your_chart_name.html", auto_open=True)

Some of you might have concerns regarding versioning or compatible formats. I found that by exporting charts as HTML, I circumvent most of these concerns as HTML files can be opened by any modern web browser, ensuring accessibility and interactive functionality even outside of the Python environment.

I appreciate the combined simplicity and power of Plotly for these tasks. When I first started using it, I thought exporting might involve a lot of steps, but it really doesn’t. It’s almost deceptively simple, which is fantastic for a beginner like me — or really for anyone who wants to ease the process of sharing and saving their work.

To sum up, the real beauty of Plotly is not just in its ability to create interactive, publication-quality charts but also in how it effortlessly accommodates the end-to-end workflow of data visualization, right through to the sharing and exporting of your final products. With just a few lines of Python, your visuals are ready to make an impact wherever they’re destined to be seen.