Plotting Using the Plotly Package in R

 

Plotting Using the Plotly Package in R

Introduction

Plotly is an interactive visualization library for R that allows the creation of high-quality, web-based graphics. Unlike base R graphics, Plotly graphs are interactive and support:

  • Zooming
  • Panning
  • Hover information
  • Legends
  • Saving graphs as images
  • Dynamic exploration

Plotly can create:

  • Scatter plots
  • Line graphs
  • Bar charts
  • Histograms
  • Pie charts
  • Box plots
  • Bubble charts
  • Heat maps
  • 3D scatter plots
  • Surface plots

Installing Plotly

install.packages("plotly")

Load the package:

library(plotly)

The plot_ly() Function

The primary function in Plotly is:

plot_ly()

Syntax

plot_ly(data,
x,
y,
type,
mode)

where

  • data : data frame
  • x : x-axis variable
  • y : y-axis variable
  • type : graph type
  • mode : line, marker, etc.

Example 1: Scatter Plot

library(plotly)

x <- c(1,2,3,4,5)
y <- c(10,15,13,17,20)

plot_ly(x=x,
y=y,
type='scatter',
mode='markers')

Produces an interactive scatter plot.




Example 2: Line Graph

plot_ly(x=x,
y=y,
type='scatter',
mode='lines')







Example 3: Line and Markers

plot_ly(x=x,
y=y,
type='scatter',
mode='lines+markers')





Example 4: Customize Marker Color and Size

plot_ly(x=x,
y=y,
type='scatter',
mode='markers',
marker=list(
color='red',
size=12
))

Example 5: Add Title and Axis Labels

fig <- plot_ly(
x=x,
y=y,
type='scatter',
mode='lines+markers')

fig <- fig %>%
layout(
title="Sales Trend",
xaxis=list(title="Year"),
yaxis=list(title="Sales")
)

fig







Example 6: Bar Chart

product <- c("A","B","C","D")
sales <- c(20,35,25,40)

plot_ly(x=product,
y=sales,
type='bar')





Example 7: Horizontal Bar Chart

plot_ly(x=sales,
y=product,
type='bar',
orientation='h')





Example 8: Pie Chart

labels <- c("A","B","C","D")
values <- c(20,30,25,25)

plot_ly(labels=labels,
values=values,
type='pie')




Example 9: Doughnut Chart

plot_ly(labels=labels,
values=values,
type='pie',
hole=0.5)




Example 10: Histogram

x <- rnorm(1000)

plot_ly(x=x,
type='histogram')



Example 11: Box Plot

marks <- c(60,65,70,75,80,85,90)

plot_ly(y=marks,
type='box')




Example 12: Multiple Box Plots

plot_ly(
y=c(60,65,70,75,80),
name="Class A",
type='box'
) %>%
add_trace(
y=c(55,60,68,72,85),
name="Class B",
type='box'
)




Example 13: Bubble Chart

plot_ly(
x=c(1,2,3,4),
y=c(10,20,15,25),
mode='markers',
marker=list(
size=c(20,40,30,50)
))

Bubble size represents an additional variable.




Example 14: Scatter Plot Using Data Frame

student <- data.frame(
Hours=c(2,4,6,8,10),
Marks=c(45,60,70,85,95)
)

plot_ly(student,
x=~Hours,
y=~Marks,
type='scatter',
mode='markers')

The symbol ~ indicates columns from a data frame.





Example 15: Add Multiple Traces

year <- c(2020,2021,2022,2023)

sales1 <- c(10,15,20,25)
sales2 <- c(12,18,22,30)

fig <- plot_ly()

fig <- fig %>%
add_trace(
x=year,
y=sales1,
type='scatter',
mode='lines+markers',
name='Product A')

fig <- fig %>%
add_trace(
x=year,
y=sales2,
type='scatter',
mode='lines+markers',
name='Product B')

fig




3D Scatter Plot

x <- c(1,2,3,4)
y <- c(5,6,7,8)
z <- c(2,4,6,8)

plot_ly(
x=x,
y=y,
z=z,
type='scatter3d',
mode='markers'
)

Interactive rotation is supported.




Surface Plot

z <- volcano

plot_ly(
z=z,
type='surface'
)



Heat Map

mat <- matrix(
1:25,
nrow=5
)

plot_ly(
z=mat,
type='heatmap'
)




Contour Plot

plot_ly(
z=volcano,
type='contour'
)



Adding Colors

plot_ly(
x=x,
y=y,
type='scatter',
mode='markers',
marker=list(color='blue')
)

Marker Properties

marker=list(
color='red',
size=15,
symbol='circle'
)

Common symbols:

  • circle
  • square
  • diamond
  • cross
  • triangle-up

Layout Function

layout(
title="Graph Title",
xaxis=list(title="X Axis"),
yaxis=list(title="Y Axis")
)


Example layout and marker

library(plotly) # Data x <- c(1, 2, 3, 4, 5) y <- c(10, 15, 13, 17, 20) # Create plot fig <- plot_ly( x = x, y = y, type = "scatter", mode = "markers", marker = list( color = "red", size = 15, symbol = "diamond" ) ) # Customize layout fig <- fig %>% layout( title = "Sales Analysis", xaxis = list( title = "Year", showgrid = TRUE ), yaxis = list( title = "Sales", showgrid = TRUE ) ) fig




Multiple Subplots

fig1 <- plot_ly(
x=1:5,
y=1:5,
type='scatter'
)

fig2 <- plot_ly(
x=1:5,
y=5:1,
type='bar'
)

subplot(fig1,fig2)



Common Plot Types

Type        Description
scatter        Scatter plot
bar        Bar chart
pie        Pie chart
histogram        Histogram
box        Box plot
heatmap        Heat map
contour        Contour plot
scatter3d        3D scatter plot
surface        Surface plot

Important Functions

FunctionPurpose
plot_ly()    Create graph
add_trace()    Add another dataset
layout()    Add titles and labels
subplot()    Multiple graphs
animation_opts()    Animation settings
saveWidget()    Save graph as HTML

Applications

  • Exploratory Data Analysis (EDA)
  • Machine Learning visualization
  • Dashboard creation
  • Scientific visualization
  • Statistical analysis
  • Financial charts
  • Interactive reports

Difference Between Base R Graphics and Plotly

Base RPlotly
Static    Interactive
Simple graphics    Dynamic graphics
No zooming    Zooming available
Limited interactivity    Hover information
Faster    More feature-rich
plot()  plot_ly()

Advantages of Plotly

  • Interactive graphs.
  • Publication-quality visualizations.
  • Supports 2D and 3D plots.
  • Works with data frames.
  • Easily integrated with Shiny dashboards.
  • Provides zooming and hover information.
  • Can export graphs as HTML.

Conclusion

The Plotly package is one of the most powerful visualization libraries available in R. Using plot_ly(), add_trace(), and layout(), users can create highly interactive 2D and 3D graphs. Plotly is widely used in data science, machine learning, statistical analysis, and dashboard development because of its flexibility and rich interactive features.

Comments

Popular posts from this blog

Statistical Methods Lab ( R Language) PCCBL308 Semester 3 KTU BTech CB and CU 2024 Scheme - Dr Binu V P

Programs in R - using control statements - Assignment 2

Basic R Programs to Try - Assignment 1