Open In App

Getting Started with Plotly in R

Last Updated : 25 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

newplot
Scatter Plot with Plotly in R

2. 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:

newplot-(1)
Box Plot with Plotly in R

3. 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:

newplot-(2)
3D Scatter Plot with Plotly in R

4. 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:

newplot-(3)
Heatmap Plot with Plotly in R

5. 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: 

add_trace


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:

animation_opts

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:

add_data

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:

save
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.


Next Article

Similar Reads