Getting Started with Plotly in R
Last Updated :
26 Mar, 2024
creationPlotly in R Programming Language allows the creation of interactive web graphics from ‘ggplot2’ graphs and a custom interface to the JavaScript library ‘plotly.js’ inspired by the grammar of graphics.
Installation
To use a package in R programming one must have to install the package first. This task can be done using the command install.packages(“packagename”). To install the whole plotly package type this:
install.packages(“plotly”)
Or install the latest development version (on GitHub) via dev tools:
devtools::install_github(“ropensci/plotly”)
Important Functions
plot_ly: It basically initiates a plotly visualization. This function maps R objects to plotly.js, an (MIT licensed) web-based interactive charting library. It provides abstractions for doing common things and sets some different defaults to make the interface feel more ‘R-like’ (i.e., closer to plot() and ggplot2::qplot()).
Syntax:
plot_ly(data = data.frame(), …, type = NULL, name, color, colors = NULL, alpha = NULL, stroke, strokes = NULL, alpha_stroke = 1, size, sizes = c(10, 00), span, spans = c(1, 20), symbol, symbols = NULL, linetype, linetypes = NULL, split, frame, width = NULL, height = NULL, source = “A”)
Scatter Plot with Colors plotly in R
R
# Load necessary libraries
library(plotly)
library(dplyr)
# Load Iris dataset
data(iris)
#Scatter Plot with Colors
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 R
plotly_build: This generic function creates the list object sent to plotly.js for rendering. Using this function can be useful for overriding defaults or for debugging rendering errors.
Syntax: plotly_build(p, registerFrames = TRUE)
Box Plot with Plotly in R
R
#Box Plot
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:
.png)
Box Plot with Plotly in R
3D Scatter Plot with Plotly in R
R
# 3D Scatter Plot
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:
.png)
3D Scatter Plot with Plotly in R
Heatmap Plot with Plotly in R
R
#Heatmap
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:
.png)
Heatmap Plot with Plotly in R
Adding trace (lines) to plotly in R
R
# import plotly library
library(plotly)
# create plotly visualisation
p <- plot_ly(iris, x = ~Sepal.Width,
y = ~Sepal.Length)
# adding trace (lines) to plotly
# visualisation
add_trace(p, type = "scatter",
mode = "markers+lines")
Output:

animation_opts: Provides animation configuration options. Animations can be created by either using the frame argument in plot_ly() or frame ggplot2 aesthetic in ggplotly(). By default, animations populate a play button and slider component for controlling the state of the animation (to pause an animation, click on a relevant location on the slider bar). Both the play button and slider component transition between frames according to rules specified by animation_opts().
Syntax:
animation_opts(p, frame = 500, transition = frame, easing = “linear”, redraw = TRUE, mode = “immediate”)
animation_slider(p, hide = FALSE, …)
animation_button(p, …, label)
R
# import plotly library
library(plotly)
plot_ly(mtcars, x = ~wt, y = ~mpg,
frame = ~cyl) %>%
animation_opts(transition = 0)
Output:

add_data: Add data to a plotly visualization.
Syntax: add_data(p, data = NULL)
R
# import plotly library
library(plotly)
plot_ly() %>% add_data(economics) %>%
add_trace(x = ~date, y = ~pce)
Output:

plotly_IMAGE: Creates a static image for plotly visualization. The images endpoint turns a plot (which may be given in multiple forms) into an image of the desired format.
Syntax:
plotly_IMAGE(x, width = 1000, height = 500, format = “png”, scale = 1, out_file, …)
R
# import plotly library
library(plotly)
# create plotly visualisation
p <- plot_ly(iris, x = ~Sepal.Width,
y = ~Sepal.Length)
# importing plotly visualisation
# as image files
Png <- plotly_IMAGE(p,
out_file = "plotly-test-image.png")
Jpeg <- plotly_IMAGE(p, format = "jpeg",
out_file = "plotly-test-image.jpeg")
# importing plotly visualisation
# as vector graphics
Svg <- plotly_IMAGE(p, format = "svg",
out_file = "plotly-test-image.svg")
# importing plotly visualisation as
# pdf file
Pdf <- plotly_IMAGE(p, format = "pdf",
out_file = "plotly-test-image.pdf")
Output:

Plotly in R
Conclusion
We can leverage the plotly R package to create a variety of interactive graphics. Two main ways of creating a plotly object: either by transforming a ggplot2 object (via ggplotly()) into a plotly object or by directly initializing a plotly object with plot_ly()/plot_geo()/plot_mapbox(). Both approaches have somewhat complementary strengths and weaknesses, so it can pay off to learn both approaches.
Similar Reads
Plot Only Text in R
In this article, we will discuss how to plot only text in the R programming language. Method 1: Using par() function with the mar argument In this approach to plot only text, the user needs to call the in-built function par function with the mar argument to simply plot the empty plot in the R progra
3 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
Scatter Slot using Plotly in R
In order to examine the relationship between two variables in data analysis, scatter plots are a fundamental visualisation tool. When we wish to visualize the distribution of data points and search for patterns, trends, or outliers, they are extremely helpful. With the help of the potent R package P
6 min read
Adding Text to Existing Figure in Plotly
Adding text to an existing figure in Plotly is a powerful way to enhance the visualization by providing additional context, explanations, or annotations. Whether you are using Plotly Express or Plotly Graph Objects, the process involves updating the layout or adding annotations. This article will gu
3 min read
Draw Plot with two Y-Axes in R
In this article, we are going to discuss how to create y-axes of both sides of a plot in R programming language. Sometimes for quick data analysis, it is required to create a single graph having two data variables with different scales. To do that in R language we use the following steps. First, we
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
Add elements to existing plotly plot in R
Plotly is a powerful library in R for creating interactive, web-based visualizations. It allows users to transform static plots into dynamic and interactive graphics, making data exploration more engaging and insightful. This article will guide you through the process of adding elements to existing
3 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
9 min read
Saving grid.arrange() Plot to File in R
Combining multiple plots into one figure is a common task in data visualization, particularly when comparing or summarizing different aspects of data. grid. arrange() from the gridExtra package in R is an effective tool for this purpose, but saving the resulting arrangement to a file can be tricky f
3 min read