Open In App

Getting Started with Plotly in R

Last Updated : 26 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:


newplot

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:


newplot-(1)

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:


newplot-(2)

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:


newplot-(3)

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: 

add_trace

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:

animation_opts

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:

add_data

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:


save

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

ML | Getting Started With AlexNet
This article is focused on providing an introduction to the AlexNet architecture. Its name comes from one of the leading authors of the AlexNet paper- Alex Krizhevsky. It won the ImageNet Large Scale Visual Recognition Challenge (ILSVRC) 2012 with a top-5 error rate of 15.3% (beating the runner up which had a top-5 error rate of 26.2%). The most im
3 min read
Getting started with Dialogflow
Dialogflow (formerly known as Api.ai), is the platform owned by Google to build conversational agents. Instead of building a chatbot from scratch, Dialogflow makes it easier to build it in considerably less time and with bunch of Google features, including pre-build ML Models that can help you get started right away. Dialogflow also allows you to i
4 min read
Getting Started with Google Actions
Actions on Google is the developer platform for the Google Assistant. By creating actions, brands are able to bring their services to the Google Assistant. Some important terms related to Actions on Google: Actions An interaction with the to start a conversation, the user needs to invoke your Action through the Assistant. Users say or type a phrase
4 min read
Getting Started With ChatGPT: A Complete Guide With Examples
Artificial Intelligence (AI) has brought about a significant transformation in the software industry and its technologies, revolutionizing the business landscape. Chatbots are one of the types of AI-powered platforms that mimic human-like conversation. Among these platforms, ChatGPT is a powerful tool that has quickly gained popularity on the inter
15+ min read
Getting Started With Google Colab
Google Colab is the short form for "Google Colabortory". It is an executable document that lets you write, run, and share code or you can think as an improved version of "Jupyter Notebook" stored in Google Drive. You might be wondering about the word "Notebook", in simple words it is just a document that includes executable lines of code along with
6 min read
Getting started with Machine Learning
From translation apps to autonomous vehicles, all powers with Machine Learning. It offers a way to solve problems and answer complex questions. It is basically a process of training a piece of software called an algorithm or model, to make useful predictions from data. This article discusses the categories of machine learning problems, and terminol
7 min read
Getting started with Classification
As the name suggests, Classification is the task of “classifying things” into sub-categories. Classification is part of supervised machine learning in which we put labeled data for training. The article serves as a comprehensive guide to understanding and applying classification techniques, highlighting their significance and practical implications
12 min read
Getting Started With Object Tracking Using OpenCV
OpenCV, developed by Intel in the early 2000s, is a popular open-source computer vision library used for real-time tasks. It offers various features like image processing, face detection, object detection, and more. In this article, we explore object-tracking algorithms and how to implement them using OpenCV and Python to track objects in videos. G
4 min read
Getting started with Kaggle : A quick guide for beginners
Kaggle is an online community of Data Scientists and Machine Learning Engineers which is owned by Google. A general feeling of beginners in the field of Machine Learning and Data Science towards the website is of hesitance. This feeling mainly arises because of the misconceptions that the outside people have about the website. Here are some of them
3 min read
How to Plot in 3D clusters using plotly package
R-Language is widely used in Data Science, Data Visualization Data Analysis many more, etc. Plotly package is highly rich in plotting various graphs, These graphs/charts are highly interactive and user-friendly. The 3D cluster visualizes the similarity between variables as 3-D spatial relationships. Each point in the graph represents an individual
2 min read