Plotly Python Tutorial: How to create interactive graphs
 Best Guide for Beginners

Lianne & Justin

Lianne & Justin

Share on twitter
Share on linkedin
Share on facebook
Share on email
plotly python tutorial graph flower
Source: Unsplash

In this tutorial, you’ll discover the popular and powerful Python graphing library: Plotly.

Plotly is a Python library that supports various interactive, publication-quality graphs for different applications. Within this guide, you’ll learn:

  • How to create a basic figure quickly with Plotly Express.
  • How to customize the figure.
  • How to add traces and update the layouts of the figure with graph objects.

If you want nice data visualizations, you’ll love this tutorial with practical procedures and examples.



Before we start

In this plotly tutorial, we assume you know the basics of Python. If not, please take our FREE Python crash course for data science.

It also helps with some knowledge of the pandas library, check out Learn Python Pandas for Data Science: Quick Tutorial.

Note: throughout this tutorial, we will be using the same scatter plot as an example to introduce the fundamentals of plotly. Once you’ve learned the basics, you can explore the other plot types by yourself.

Without further ado, it’s time to graph!


Load the Dataset

In this plotly Python tutorial, we’ll use the Boston house-prices dataset (regression) from the scikit-learn (sklearn) library as an example.

To use it, we need to:

  • import both the dataset and the pandas libraries.
  • and load the dataset as a Bunch object named boston.
    You can read more about the object in the load_boston documentation. But it’s not necessary for this tutorial.

The Bunch object is not convenient for analyses in Python. So we’ll convert it to a pandas DataFrame with the same variables, plus the target variable renamed as med_value.

Let’s print out the information summary of the dataset df as well.

As you can see below, the dataset has 506 rows and 14 columns, with no missing values.

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 506 entries, 0 to 505
Data columns (total 14 columns):
 #   Column     Non-Null Count  Dtype  
---  ------     --------------  -----  
 0   CRIM       506 non-null    float64
 1   ZN         506 non-null    float64
 2   INDUS      506 non-null    float64
 3   CHAS       506 non-null    float64
 4   NOX        506 non-null    float64
 5   RM         506 non-null    float64
 6   AGE        506 non-null    float64
 7   DIS        506 non-null    float64
 8   RAD        506 non-null    float64
 9   TAX        506 non-null    float64
 10  PTRATIO    506 non-null    float64
 11  B          506 non-null    float64
 12  LSTAT      506 non-null    float64
 13  med_value  506 non-null    float64
dtypes: float64(14)
memory usage: 55.5 KB

Don’t worry about the details of the dataset. Just know that we can use it to make plotly graphs.

Plotly Express

When graphing with plotly, the commonly recommended starting point is Plotly Express (PX).

This module is a built-in part of the plotly library, which offers a high-level interface to create entire figures at once. It’s efficient yet powerful to support over 30 different chart functions. As long as you don’t need complicated charts and/or lots of customizations, PX is enough for you.

So without worrying too much about the figures’ look, let’s make our first plotly figure with Plotly Express!

As usual, we need to import the module first. Then we can use px.scatter to make a scatter plot. The px.scatter takes in our pandas DataFrame df as the dataset, with the x and y arguments specified as the axes. It returns a plotly figure object, which can be displayed in Jupyter Notebook using the show method.

Nice!

Now you should be able to see your first plotly figure like below.

plotly python tutorial scatter plot graph example

Don’t forget that it’s interactive!

If you hover over the dots, you can see the coordinates of the axes. You can also try the buttons on the top right corner to explore more of the figure.

Further Reading: for other Plotly Express functions/charts such as bar chart, line chart, check out the official documentation. Again, it’s not difficult to plot other basic types of charts once you grasp the concepts. So let’s move on with the tutorial.

Now, what if we want to add more details to the figure?

There’re many parameters that the px.scatter function offers to customize the chart. You can either go to the website or print out the help page using the Python code below.

Let’s try some of these parameters out.

Below is an example where we set the title, width, and height of the figure.

plotly python tutorial scatter plot graph plotly express example

Although Plotly Express allows us to create charts quickly with some customizations, we sometimes want to change the figures even more. For example, px.scatter can’t customize the background color of the graph. Also, Plotly Express doesn’t have functions to create some more complicated charts such as combination charts with a line and a bar, which will be shown in an example.

So it’s time to dig deeper into plotly.

Plotly Figure Objects

As shown in the previous section, we can create a plotly figure object with Plotly Express.

What is a figure?

The figure object is a data structure that holds information on what and how to display in the graphs. The plotly Python package helps create, manipulate, and render this object as charts, plots, maps, etc.

Figures have tree-like structures with nodes called “attributes”. The root node of the tree has three top-level attributes that control different parts of the graphs:

  • data, which holds the data and type(s) of charts. Plotly calls these sets of data and chart type values as ‘traces’.
  • layout, which specifies other non-data related chart elements, including title, fonts, and plot size.
  • frames, which are used for animated plots. We won’t cover it in this tutorial.

For example, we can print out the fig object we created in the previous example.

It contains both the data attribute as a list of dictionaries and the layout attribute below.

Figure({
    'data': [{'hovertemplate': 'LSTAT=%{x}<br>med_value=%{y}<extra></extra>',
              'legendgroup': '',
              'marker': {'color': '#636efa', 'symbol': 'circle'},
              'mode': 'markers',
              'name': '',
              'orientation': 'v',
              'showlegend': False,
              'type': 'scatter',
              'x': array([4.98, 9.14, 4.03, ..., 5.64, 6.48, 7.88]),
              'xaxis': 'x',
              'y': array([24. , 21.6, 34.7, ..., 23.9, 22. , 11.9]),
              'yaxis': 'y'}],
    'layout': {'height': 500,
               'legend': {'tracegroupgap': 0},
               'template': '...',
               'title': {'text': 'Relationship between LSTAT and med_value'},
               'width': 500,
               'xaxis': {'anchor': 'y', 'domain': [0.0, 1.0], 'title': {'text': 'LSTAT'}},
               'yaxis': {'anchor': 'x', 'domain': [0.0, 1.0], 'title': {'text': 'med_value'}}}
})

Plotly Graph Objects

So how do we add more customizations to the plotly figure?

We need to use the lower-level plotly graph objects to change the figure data structure.

The plotly graph object is the Python classes that represent different parts of the figure. Actually, we’ve already been using it. When we used Plotly Express functions to create figures, Python used graph objects behind the scenes and returned a plotly.graph_objects.Figure.

Create Figure

In fact, we can always create the same figure built by Plotly Express using the graph objects directly. Yet the graph objects method requires much longer code compared to the 1-line Plotly Express function.

We need to first import the plotly.graph_objects, and build the figure from bottom up. Starting from an empty figure, we used the two common types of methods update_* and add_* to add things to it.

As you can see, these many lines of code created the same figure below as the 1-line code using Plotly Express. Now you know why Plotly Express is a better starting point most of the time!

plotly python tutorial scatter plot graph objects example

Next, let’s see what other modifications the graph objects can bring to the figure.

Add Data/Traces

First, we’ll use the add_trace method again to add two more “traces”:

  • trace1: a Scatter trace with the mode = ‘lines’ to draw a line.
  • trace2: a Bar trace.

As shown below, the figure has two new traces added. It becomes a combination chart of a line, a bar, and a scatter plot.

plotly python tutorial scatter plot graph objects add traces

And if we print out the object again, we can see that the new traces are added into the figure object’s data attribute.

Figure({
    'data': [{'hovertemplate': 'LSTAT=%{x}<br>med_value=%{y}<extra></extra>',
              'legendgroup': '',
              'marker': {'color': '#636efa', 'symbol': 'circle'},
              'mode': 'markers',
              'name': '',
              'orientation': 'v',
              'showlegend': False,
              'type': 'scatter',
              'x': array([4.98, 9.14, 4.03, ..., 5.64, 6.48, 7.88]),
              'xaxis': 'x',
              'y': array([24. , 21.6, 34.7, ..., 23.9, 22. , 11.9]),
              'yaxis': 'y'},
             {'mode': 'lines', 'type': 'scatter', 'x': [0, 50], 'y': [0, 50]},
             {'type': 'bar', 'x': [10, 20, 30], 'y': [10, 20, 30]}],
    'layout': {'legend': {'tracegroupgap': 0},
               'template': '...',
               'title': {'text': 'Relationship between LSTAT and med_value + Another Trace'},
               'xaxis': {'anchor': 'y', 'domain': [0.0, 1.0], 'title': {'text': 'LSTAT'}},
               'yaxis': {'anchor': 'x', 'domain': [0.0, 1.0], 'title': {'text': 'med_value'}}}
})

Update Layouts

Next, we’ll explore the update methods to customize the layouts of the figure even more.

We can update the background colors of the figure.

plotly python tutorial scatter plot graph objects update layout

We can also update the x-axis with tick bars.

plotly python tutorial scatter plot graph objects update layout

Another useful customization is to add annotations at certain locations on the plot. In the Python code below, we added an annotation ‘This is a special point’ to mark one of the points on the figure.

plotly scatter plot graph objects update layout

Again, we can print out the figure object to take a look.

We can see that all the updated layouts are shown in the layout attribute.

Figure({
    'data': [{'hovertemplate': 'LSTAT=%{x}<br>med_value=%{y}<extra></extra>',
              'legendgroup': '',
              'marker': {'color': '#636efa', 'symbol': 'circle'},
              'mode': 'markers',
              'name': '',
              'orientation': 'v',
              'showlegend': False,
              'type': 'scatter',
              'x': array([4.98, 9.14, 4.03, ..., 5.64, 6.48, 7.88]),
              'xaxis': 'x',
              'y': array([24. , 21.6, 34.7, ..., 23.9, 22. , 11.9]),
              'yaxis': 'y'},
             {'mode': 'lines', 'type': 'scatter', 'x': [0, 50], 'y': [0, 50]},
             {'type': 'bar', 'x': [10, 20, 30], 'y': [10, 20, 30]}],
    'layout': {'annotations': [{'text': 'This is a special point', 'x': 14.79, 'y': 30.7}],
               'legend': {'tracegroupgap': 0},
               'paper_bgcolor': 'LightSteelBlue',
               'plot_bgcolor': 'white',
               'template': '...',
               'title': {'text': 'Relationship between LSTAT and med_value + Another Trace'},
               'xaxis': {'anchor': 'y',
                         'domain': [0, 0.5],
                         'tickcolor': 'green',
                         'ticklen': 20,
                         'ticks': 'inside',
                         'tickwidth': 5,
                         'title': {'text': 'LSTAT'}},
               'yaxis': {'anchor': 'x', 'domain': [0.0, 1.0], 'title': {'text': 'med_value'}}}
})

Besides these examples, there’re also other customizations, you can print out and read the help page using the code below.


To summarize, we should start from Plotly Express most of the time to create the plotly figures, and then use graph objects to customize it. For exceptions, check out When to use Graph Objects Directly.

That’s all for the Plotly Python tutorial! Now it’s time for you to make your own graphs.

Leave a comment for any questions you may have or anything else.

Share on twitter
Twitter
Share on linkedin
LinkedIn
Share on facebook
Facebook
Share on email
Email
Lianne & Justin

Lianne & Justin

Leave a Comment

Your email address will not be published. Required fields are marked *

More recent articles

Scroll to Top
We use cookies to ensure you get the best experience on our website.  Learn more.