ggplot join line and point plot with conditional colours

Viewed 47
 dat <- structure(list(yearID = c(2014L, 2015L, 2016L, 2017L, 2018L, 
                  2019L, 2013L), yield = c(0.328575295095694, 0.0853721681507231, 
                  1.26616635028825, 0.609179296764281, 0.519918049485935, 0.77932406868591, 
                  0.94), flag = c("sim", "sim", "sim", "sim", "sim", "sim", "obs"
                  )), row.names = c(NA, -7L), class = c("tbl_df", "tbl", "data.frame"
                  ))

  
library(ggplot2)

ggplot(dat, aes(x = yearID, y = yield, col = flag)) +
geom_point() + geom_line() + theme(legend.position = 'top')

enter image description here

How can I connect all points and also distinguish between them using the flag column

1 Answers

Also in the general aes() from initial ggplot or follow the great suggestion from @Bas:

library(ggplot2)
#Code
ggplot(dat, aes(x = yearID, y = yield, col = flag,group=1)) +
  geom_point() + geom_line() + theme(legend.position = 'top')

Output:

enter image description here

Related