Reputation: 141
I want to create a line chart with two lines in one plot using ggplot. However, one line chart has missing values in-between:
year<-c(1990,1991,1992,1993)
v1<-c(1,NA,NA,2)
v2<-c(2,3,1,2)
I want the second line (v2) to connect its first value in 1990 with its last one in 1993. Is this possible using ggplot?
Upvotes: 1
Views: 278
Reputation: 39595
Try this approach reshaping your data:
library(ggplot2)
library(dplyr)
library(tidyr)
#Data
year<-c(1990,1991,1992,1993)
v1<-c(1,NA,NA,2)
v2<-c(2,3,1,2)
df <- data.frame(year,v1,v2)
#Plot
df %>% pivot_longer(-year) %>%
filter(!is.na(value)) %>%
ggplot(aes(x=factor(year),y=value,color=name,group=name))+
geom_point()+
geom_line()+xlab('year')+
labs(color='Var')
Output:
Upvotes: 2