Getting Started with Plotly in R
Last Updated :
25 Jun, 2025
Plotly in R Programming Language allows the creation of interactive web graphics from ggplot2 graphs and provides a custom interface to the JavaScript library plotly.js. This library is inspired by the grammar of graphics, making it easy to produce high-quality, interactive visualizations.
Installation
To use Plotly in R, we first need to install the package. This can be done using the following command:
install.packages("plotly")
Or install the development version of Plotly from GitHub for early access to new features and fixes:
devtools::install_github("ropensci/plotly")
Note: If we choose to install the development version, we should make sure the devtools package is installed. We can install it with:
install.packages("devtools")
Understanding Plot_ly Function
The plot_ly function initializes a Plotly visualization in R. It maps R objects to Plotly.js, enabling interactive and dynamic charts. It provides abstractions for common tasks and sets default options that make the interface feel more familiar to R users, aligning it with the syntax and behavior of functions like plot() and ggplot2::qplot().
Syntax:
plot_ly(data = data.frame(), x = NULL, y = NULL, color = NULL, type = NULL, mode = NULL, marker = NULL)
Parameters:
- data: The dataset to be visualized.
- x and y: Variables for the axes.
- color: Aesthetic for coloring data points.
- type: The type of plot (e.g., "scatter", "bar", "line").
- mode: The mode of the plot (e.g., "markers", "lines", "markers+lines").
- marker: A list to specify marker properties such as size and opacity.
1. Scatter Plot with Colors Using Plotly in R
Scatter plots help visualize relationships between two variables. This example uses the iris dataset to plot Sepal Length vs. Sepal Width, with points colored by species for clear group distinction.
R
library(plotly)
library(dplyr)
data(iris)
plot_ly(iris, x = ~Sepal.Length, y = ~Sepal.Width, color = ~Species,
type = "scatter", mode = "markers",
marker = list(size = 10, opacity = 0.8)) %>%
layout(title = "Scatter Plot of Sepal Length vs. Sepal Width",
xaxis = list(title = "Sepal Length"),
yaxis = list(title = "Sepal Width"))
Output:
Scatter Plot with Plotly in R2. Box Plot with Plotly in R
Box plots are useful for comparing data distributions across categories. This example uses the iris dataset to show Petal Length by Species, with jittered points and a standard deviation line for added insight.
R
plot_ly(iris, x = ~Species, y = ~Petal.Length,
type = "box", boxpoints = "all", jitter = 0.3,
pointpos = -1.8, boxmean = "sd") %>%
layout(title = "Box Plot of Petal Length by Species",
xaxis = list(title = "Species"),
yaxis = list(title = "Petal Length"))
Output:
Box Plot with Plotly in R3. 3D Scatter Plot with Plotly in R
3D scatter plots are useful for visualizing relationships among three continuous variables. This example uses the iris dataset to plot Sepal Length, Sepal Width and Petal Length in a 3D space, with points colored by species.
R
plot_ly(iris, x = ~Sepal.Length, y = ~Sepal.Width, z = ~Petal.Length,
color = ~Species, type = "scatter3d", mode = "markers",
marker = list(size = 8, opacity = 0.8)) %>%
layout(title = "3D Scatter Plot of Sepal Length, Sepal Width, and Petal Length",
scene = list(xaxis = list(title = "Sepal Length"),
yaxis = list(title = "Sepal Width"),
zaxis = list(title = "Petal Length")))
Output:
3D Scatter Plot with Plotly in R4. Heatmap Plot with Plotly in R
Heatmaps are useful for visualizing correlations or intensity patterns between variables. This example uses the iris dataset to display a correlation matrix of its numeric features with a Viridis color scale.
R
plot_ly(z = ~cor(iris[, 1:4]), type = "heatmap",
colorscale = "Viridis", showscale = FALSE) %>%
layout(title = "Correlation Heatmap of Iris Features",
xaxis = list(ticktext = colnames(iris[, 1:4]),
tickvals = seq(0.5, 4.5, by = 1),
title = "Features"),
yaxis = list(ticktext = colnames(iris[, 1:4]),
tickvals = seq(0.5, 4.5, by = 1),
title = "Features"))
Output:
Heatmap Plot with Plotly in R5. Adding Traces to Plotly Charts in R
Traces allow us to add new layers to an existing Plotly chart. This example adds both markers and lines to a scatter plot of Sepal Width vs. Sepal Length using the iris dataset.
R
library(plotly)
p <- plot_ly(iris, x = ~Sepal.Width,
y = ~Sepal.Length)
add_trace(p, type = "scatter",
mode = "markers+lines")
Output:

6. Animation in Plotly with animation_opts
animation_opts function allows us to control the behavior of animations in Plotly. Animations can be created by using the frame argument in plot_ly() or by using ggplotly() with a frame aesthetic. By default, animations in Plotly include a play button and a slider which enable us to pause, play and navigate through the frames. The frames transition according to the settings specified in animation_opts().
Syntax:
animation_opts(p, frame = 500, transition = frame, easing = “linear”, redraw = TRUE, mode = “immediate”)
Parameters:
- frame: The time for each frame to display (in milliseconds).
- transition: The speed at which one frame changes to the next.
- easing: The type of animation effect (e.g., "linear" for a smooth transition).
- redraw: If set to TRUE, the plot redraws for each new frame.
- mode: When the animation should start. The default is "immediate".
Example: This code creates an animated plot using the mtcars dataset, displaying the relationship between weight (wt) and miles per gallon (mpg), with animation controlled by the cyl variable (cylinder count). The animation_opts() function is used to set the transition speed to 0.
Python
library(plotly)
plot_ly(mtcars, x = ~wt, y = ~mpg, frame = ~cyl) %>%
animation_opts(transition = 0)
Output:

7. Adding Data to a Plotly Visualization with add_data
The add_data() function allows us to add additional data to an existing Plotly visualization. This is useful when we want to layer new data or update a plot after its initial creation.
Syntax:
add_data(p, data = NULL)
Parameters:
- p: The existing Plotly plot object.
- data: The new data to be added to the plot.
Example: In this example, we will add the economics dataset to a Plotly plot and then add a trace (line plot) of date vs. pce (personal consumption expenditures).
R
library(plotly)
plot_ly() %>%
add_data(economics) %>%
add_trace(x = ~date, y = ~pce)
Output:

8. Saving Plotly Charts as Image Files in R
plotly_IMAGE function allows exporting an interactive Plotly visualization into a static image file. It supports multiple formats such as PNG, JPEG (raster), as well as SVG and PDF (vector graphics). This is useful for embedding charts into documents, presentations or reports where interactivity is not required.
Syntax:
plotly_IMAGE(x, width = 1000, height = 500, format = "png", scale = 1, out_file, ...)
Parameters:
- x: The Plotly object to export.
- width and height: Dimensions of the output image in pixels.
- format: Output format are "png", "jpeg", "svg" or "pdf".
- scale: Scaling factor for the image.
- out_file: The path where the file will be saved.
Example: The following example demonstrates how to export a Plotly chart as PNG, JPEG, SVG and PDF using the plotly_IMAGE() function, by specifying different output formats and file names.
R
library(plotly)
p <- plot_ly(iris, x = ~Sepal.Width,
y = ~Sepal.Length)
Png <- plotly_IMAGE(p,
out_file = "plotly-test-image.png")
Jpeg <- plotly_IMAGE(p, format = "jpeg",
out_file = "plotly-test-image.jpeg")
Svg <- plotly_IMAGE(p, format = "svg",
out_file = "plotly-test-image.svg")
Pdf <- plotly_IMAGE(p, format = "pdf",
out_file = "plotly-test-image.pdf")
Output:
Plotly in R
The output shows a static scatter plot of Sepal Width vs. Sepal Length, exported as image files in various formats (PNG, JPEG, SVG and PDF) using the plotly_IMAGE() function.
Similar Reads
Scatter Plot using Plotly in R A scatter plot in R is a graphical tool used to display the relationship between two continuous variables. Each point represents one observation, with its position determined by values on the x and y axes.Uses of Scatter PlotWe can use a scatter plot for the followingTo observe the relationship betw
5 min read
Saving a Plot in R (With Examples) In this article, we will be looking at the approach to save plots in data objects in R Programming Language. Using recordPlot() functionThis approach is the easiest way to save any type of plot given in the data object form using the recordPlot() function. In this approach, to save the plot in the d
3 min read
Getting LaTeX into R Plots Data visualization is a cornerstone of exploratory data analysis, enabling analysts to effectively glean insights and communicate findings. Mathematical notation often accompanies visualizations in scientific and technical fields, elucidating complex relationships and phenomena. Understanding LaTeX
3 min read
Stacked bar plot Using Plotly package in R In general, the bar plots are used to plot the categorical data. The stacked bar plot is a type of bar plot which is used to visualize the data effectively in the same bar by plotting them in a stacked manner. These are mostly used when one wants to summarize similar kinds of data by plotting a sing
4 min read
Mirror bar plot with plotly in R Creating a mirror bar plot in R using the Plotly library can be a visually effective way to compare two sets of data, such as positive and negative values, in a single chart. This article will guide you through the process of creating a mirror bar plot with Plotly in R, including setting up the envi
5 min read
Interactive Data Visualization with Plotly Express in R Data Visualization in R is the process of representing data so that it is easy to understand and interpret. Various packages are present in the R Programming Language for data visualization. Plotly's R graphing library makes interactive, publication-quality graphs. Plotly can be used to make various
8 min read