How to define points outside the R data frame and draw them in ggplot2 graph?


To define points outside the R data frame and draw them in ggplot2 graph, we can follow the below step −

  • First of all, create a data frame
  • Then, create the scatterplot using geom_point function of ggplot2 package.
  • Create the scatterplot with data outside data frame using data.frame inside geom_point.

Create the data frame

Let's create a data frame as shown below −

 Live Demo

x<-round(rnorm(25,1,0.005),2)
y<-round(rnorm(25,5,0.25),2)
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) −

    x    y
1 1.01 4.94
2 1.00 5.21
3 1.00 4.56
4 1.00 5.42
5 0.99 5.22
6 1.00 4.96
7 0.99 4.64
8 1.01 5.16
9 1.00 5.12
10 1.00 5.00
11 0.99 5.04
12 1.00 4.85
13 1.00 5.09
14 1.00 5.07
15 1.01 4.93
16 1.00 4.67
17 0.99 5.18
18 1.00 5.14
19 1.00 4.79
20 1.00 4.60
21 1.01 5.05
22 1.00 4.91
23 1.00 5.06
24 1.00 4.68
25 1.00 4.76

Create the scatterplot

Use geom_point function of ggplot2 package to create the scatterplot between x and y −

x<-round(rnorm(25,1,0.005),2)
y<-round(rnorm(25,5,0.25),2)
df<-data.frame(x,y)
library(ggplot2)
ggplot(df,aes(x,y))+geom_point()

Output

Create the scatterplot with data outside data frame

Using data.frame function to create new data set inside geom_point and plot them. −

x<-round(rnorm(25,1,0.005),2)
y<-round(rnorm(25,5,0.25),2)
df<-data.frame(x,y)
library(ggplot2)
ggplot(df,aes(x,y))+geom_point()+geom_point(data=data.frame(x=c(0.995,1.02),y=c(4.9
,5.2)),colour="blue")

Output

Updated on: 14-Aug-2021

167 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements