Add & Remove Trace in plotly Graph in Python (3 Examples)

 

Hi! This tutorial will show you how to append and delete a trace element in a plotly graph in the Python programming language.

Here is an overview:

Let’s get right into the Python code!

 

Install & Import plotly

To install and import the Python plotly library, run the lines of code below in your preferred Python coding IDE:

# install plotly
pip install plotly
 
# import plotly
import plotly.express as px
import plotly.graph_objects as go

In the above code, we imported plotly express and plotly graph objects because we will use plotly express to build a basic graph and then use plotly graph objects to add a trace on top of the graph.

So, with plotly now installed and imported into our Python programming environment, we can go on to build visualizations.

 

Load Example Dataset

We will make use of the popular iris dataset, which comes pre-loaded in plotly.

So, to load and preview the first 10 rows of the DataFrame, run the lines of code below:

df = px.data.iris()
 
print(df.head(10))
 
# sepal_length	 sepal_width	 petal_length	 petal_width   species	 species_id
#0	   5.1	         3.5	          1.4	         0.2   setosa	          1
#1	   4.9	         3.0	          1.4	         0.2   setosa	          1
#2	   4.7	         3.2	          1.3	         0.2   setosa	          1
#3	   4.6	         3.1	          1.5	         0.2   setosa	          1
#4	   5.0	         3.6	          1.4	         0.2   setosa	          1
#5	   5.4	         3.9	          1.7	         0.4   setosa	          1
#6	   4.6	         3.4	          1.4	         0.3   setosa	          1
#7	   5.0	         3.4	          1.5	         0.2   setosa	          1
#8	   4.4	         2.9	          1.4	         0.2   setosa	          1
#9	   4.9	         3.1	          1.5	         0.1   setosa	          1

With the dataset loaded, we can now build our plotly graph.

 

Example 1: Build Basic Plot

In this first example, we will build a basic scatter plot. Therefore, run the lines of code below:

fig = px.scatter(df, x = "sepal_length", y = "petal_width", color = "species")
 
fig.show()

In the above example, we used the px.scatter() function to create the scatter plot.

In it, we passed the DataFrame, and defined the X and Y arguments as sepal_length and petal_width respectively. We also colored the plot by the species.

Let us now add a trace element on top of the plot.
 

Example 2: Add Trace Element to Plot

In this next example, we will add a trace element to the plot:

fig = px.scatter(df, x = "sepal_length", y = "petal_width", color = "species")
 
fig.add_trace(
    go.Scatter(
        x=[4.5, 8],
        y=[0, 2],
        mode="lines",
        line=go.scatter.Line(color="gray"),
        showlegend=False)
)
 
fig.show()

Here, we have added a trace element on top of the original graph using the add_trace() function wherein we passed the go.Scatter() function that was used to plot the line based on the given X and Y coordinates on the original plot.
 

Example 3: Remove Trace Element from Plot

In this final example, we will demonstrate how to remove the trace element we added in the previous example:

fig.data[3].visible = False
 
fig.show()

As you can see, we have removed the trace element we added to the plot. All we needed to do was pass its index position to fig.data[] structure, and then set its visibility to False.

If you are not sure about the index of the trace element, you can run the following code to figure that out.

for i, trace in enumerate(fig.data):
    print(f"Index {i} - {trace['type']} named '{trace['name']}'")

That way, you can be sure about the index of the trace element and remove it from the plot.

 

Video, Further Resources & Summary

Do you need more explanations on how to attach and detach a trace element in a plotly graph in Python? Then, you should have a look at the following YouTube video of the Statistics Globe YouTube channel.

In the video, we explain how to add and remove traces in a plotly graph in Python.

 

The YouTube video will be added soon.

 

You can check out these other articles for more detailed examples and videos of other popular charts in plotly using the Python programming language:

This post has shown how to add and remove traces in a plotly graph in Python. In case you have further questions, you may leave a comment below.

 

R & Python Expert Ifeanyi Idiaye

This page was created in collaboration with Ifeanyi Idiaye. You might check out Ifeanyi’s personal author page to read more about his academic background and the other articles he has written for the Statistics Globe website.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

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

Fill out this field
Fill out this field
Please enter a valid email address.

Top