# Add & Remove Trace in plotly Graph in R (3 Examples)

Hi! This tutorial will show you how to add & remove a trace element in a plotly graph in the R programming language.

Here is an overview:

Letâ€™s get into the R code!

## Install & Load plotly & dplyr

To install and load the R plotly and dplyr libraries, run the lines of code below in your preferred R code editor or IDE:

```# install plotly & dplyr
install.packages(c("plotly", "dplyr"))

library(plotly)

library(dplyr)```

The R dplyr library is the go-to library in R programming for data analysis and manipulation. It also makes it possible to use the pipe operator (|> or %>%) to connect lines of code together and run them as one chunk.

Now that we have installed and loaded both plotly and dplyr into our R programming environment, we can use them both in this tutorial example.

First, though, we need an example dataset to work with.

## Create Example Data

We will make use of the popular iris dataset that comes preloaded in R Studio IDE.

To load and preview the first 10 rows of the data, run the lines of code below:

```df <- iris

#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#1           5.1         3.5          1.4         0.2  setosa
#2           4.9         3.0          1.4         0.2  setosa
#3           4.7         3.2          1.3         0.2  setosa
#4           4.6         3.1          1.5         0.2  setosa
#5           5.0         3.6          1.4         0.2  setosa
#6           5.4         3.9          1.7         0.4  setosa
#7           4.6         3.4          1.4         0.3  setosa
#8           5.0         3.4          1.5         0.2  setosa
#9           4.4         2.9          1.4         0.2  setosa
#10          4.9         3.1          1.5         0.1  setosa```

With the example data loaded, we can now demonstrate how to add and remove traces in plotly in R.

## Example 1: Build Basic plotly Plot

Here, we will build a basic scatter plot as the base plot. Since we will be adding a trace element on top of the base plot, we will need to label each plotly figure object:

```fig1 <- df |>
plot_ly(x = ~Sepal.Width,
y = ~Petal.Length,
color = ~Species,
type = "scatter",
mode = "markers") |>
layout(title = "Sepal Width Vs Petal Length")

fig1```

To build the base scatter plot, we piped the plot_ly() function to the data frame `df`, and in it, we defined the x and y axes of the plot as `Sepal.Width` and `Petal.Length` respectively.

We also colored the plot by the `Species` column in the data and then piped the layout() function wherein we gave the plot a title.

With the base plot created, the next thing is to add a trace element to the plotly figure object.

## Example 2: Add Trace to plotly Plot

Now, we will add lines as a trace element to the existing plot:

```fig2 <- fig1 |>
x = ~Sepal.Width,
y = ~Petal.Length,
color = ~Species,
type = "scatter",
mode = "lines",
name = "Trace 2")

fig2```

In order to add traces on top of the original graph, we used the add_trace() function to connect data points via lines in the existing plotly figure object.

In the `add_trace()` function, we defined the x and y axes, just as we had done before; then we set the plot type to `"scatter"` and mode to `"lines"`. This, thus, added a line plot on top of the existing scatter plot.

## Example 3: Remove Trace from plotly Plot

Having seen how to add a trace element to an existing plot, we will now demonstrate how to remove the added trace element from the plot.

To do so, we will create a 3rd plotly figure object:

```fig3 <- fig2\$preRenderHook(fig1)

fig3```

For us to remove the added trace, we applied the preRenderHook() method to the original base plot.

Pre-render hooks are typically used to customize or modify the appearance or behavior of a plot before it is rendered or displayed.

So, in our case, the function modifies the `fig2` plotly figure object by removing the trace element and returning the original base plot, and then storing it in `fig3`.

In effect, `fig2` has inherited some behavior or customization from `fig1`, which includes not having an added trace element.

The `preRenderHook()` method is typically used when you want to apply custom JavaScript code to a plot before it is rendered. Itâ€™s a way to extend the functionality of a plotly plot.

So, by running that line of code, we have removed the added trace element from the original plotly graph.

## Video, Further Resources & Summary

Do you need more explanations on how to add and remove a trace element from a plotly graph in R? Then you should have a look at the following YouTube video of the Statistics Globe YouTube channel.

In the video, we explain in some more detail how to add and remove a trace element from a plotly graph in R.

So, we have demonstrated how to add and remove a trace element from a plotly graph in R. Furthermore, you could have a look at some of the other interesting R plotly tutorials on Statistics Globe:

This post has shown how to add and remove a trace element from a plotly graph in R. I hope you found it helpful! In case you have further questions, you may leave a comment below.

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