How to convert ggplot2 graph into a plotly graph in R?


To convert ggplot2 graph into a plotly graph in R, we can follow the below steps −

  • First of all, create a data frame.
  • Then, create a ggplot2 graph and save it in an object.
  • After that, load plotly package and create the ggplot2 graph using ggplotly function.

Create the data frame

Let's create a data frame as shown below −

 Live Demo

x<-rnorm(25)
y<-rnorm(25)
df<-data.frame(x,y)
df

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

Output

         x          y
1 0.160361011 -0.88189510
2 0.771392061 0.69962247
3 -0.308439127 0.22427952
4 -0.837255067 0.67392311
5 0.495957782 1.04842600
6 -0.189008279 -0.77466960
7 -1.549495414 -0.19465584
8 -1.872725294 -0.33989568
9 1.940702795 -0.44784231
10 0.442866654 -1.39346251
11 -0.193691298 0.07398365
12 -0.476113218 1.09803808
13 -0.892223940 0.17936301
14 0.001449752 -0.30526590
15 -1.544441879 0.18589968
16 -1.815990647 0.35021341
17 -0.737028805 -1.20777165
18 -0.120356999 2.30394059
19 1.003978769 -0.10736088
20 0.443776893 0.08895760
21 1.403476566 -0.92807236
22 -1.182746347 1.90537257
23 0.706294800 0.12941663
24 -0.620933679 -0.83009552
25 -0.350476727 1.84697007

Create the graph using ggplot2

Loading ggplot2 package and creating scatterplot between x and y −

x<-rnorm(25)
y<-rnorm(25)
df<-data.frame(x,y)
library(ggplot2)
Plot<-ggplot(df,aes(x,y))+geom_point()
Plot

Output

Converting ggplot2 graph into plotly graph

Loading plotly package and creating the ggplot2 graph using ggplotly function −

x<-rnorm(25)
y<-rnorm(25)
df<-data.frame(x,y)
library(ggplot2)
Plot<-ggplot(df,aes(x,y))+geom_point()
library(plotly)
ggplotly(Plot)

Output

Updated on: 11-Aug-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements