1

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?

1 Answer 1

2

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:

enter image description here

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the solution. However, I would like to expand the line chart to even three lines (i.e. one year column and three value columns). Is your solution applicable to that?
Yes, it should work regardless of the number of columns as long as there are no other columns besides year and your value columns. Otherwise, you have to edit the pivot_longer() call.
@nohomejerome I f you have more years or more variables it will work as data was reshaped. Let me know if you have other question!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.