In this post, I am going to explain how to plot two lines within a same plot with different range of x-axis in ggplot2. When we search online, there are many example codes that provide a solution to the dual line plots sharing same x-axis, but there is not much to refer to with different range of x-axis.

# simulate two sample datasets 
set.seed(123)
x1 = seq(1, 15, 1)
y1 = sample.int(30, 15, replace=TRUE)
try1 = data.frame(x=x1, y=y1)
try1
##     x  y
## 1   1  9
## 2   2 24
## 3   3 13
## 4   4 27
## 5   5 29
## 6   6  2
## 7   7 16
## 8   8 27
## 9   9 17
## 10 10 14
## 11 11 29
## 12 12 14
## 13 13 21
## 14 14 18
## 15 15  4
x2 = seq(1, 6, 1)
y2 = sample.int(30, 6, replace=TRUE)
try2 = data.frame(x=x2, y=y2)
try2
##   x  y
## 1 1 27
## 2 2  8
## 3 3  2
## 4 4 10
## 5 5 29
## 6 6 27

We would like to plot y with respect to x for this two datasets within a same figure. We noticed that the range of x-axis in the two plots are different. The following code provides a remedy for that.

# add another feature variable to differentiate the two datasets
try1$feature="dataset1"
try2$feature="dateset2"

#combine the two datasets, this reflects we can combine two 
# data.frame by row
df= rbind(try1, try2)
# plot the two lines
library(ggplot2)
ggplot(df) + geom_line(aes(x, y, colour=feature))