Home > database >  ggplot2 each group consists of only one observation-plotting two lines on one graph [duplicate]
ggplot2 each group consists of only one observation-plotting two lines on one graph [duplicate]

Time:09-28

Beginner R user here. I am trying to graph two simple lines using the following data frame:

date_of_case <- c("7/12/2020", "7/13/2020", "7/14/2020", "7/15/2020", "7/16/2020", "7/17/2020", "7/18/2020", "7/19/2020", "7/20/2020", "7/21/2020", "7/22/2020", "7/23/2020", "7/24/2020", "7/25/2020", "7/26/2020", "7/27/2020", "7/28/2020", "7/29/2020", "7/30/2020", "7/31/2020", "8/01/2020", "8/02/2020", "8/03/2020")
Masked <- c(25, 23, 20, 20.5, 20, 20, 20.5, 20, 20.5, 21.25, 20, 20, 20.5, 19, 20.5, 18, 16, 16, 16, 16, 16, 16, 16)
NoMask <- c(9.5, 9, 9, 10, 10, 10, 9.5, 9.5, 9, 9, 9, 9, 9.5, 10, 10, 10, 9.5, 9.5, 10, 9, 9, 9, 9)
df <- data.frame(date_of_case, Masked, NoMask)

I then want to plot both Masked and Unmasked vectors (y aesthetic) on my date vector (x aesthetic). I do this as follows:

ggplot(df, aes(x=date_of_case))  
  geom_line(aes(y=Masked, colour="Masked"))  
  geom_line(aes(y=NoMask, colour="NoMask"))

Unfortunately, I keep getting this error message: "geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?"

When I replace geom_line by geom_point, it works nicely (see below).enter image description here

Thanks in advance and apologies if this seems trivial to most.

CodePudding user response:

You need to add group = 1 inside aes:

ggplot(df, aes(x=date_of_case, group = 1))  
  geom_line(aes(y=Masked, colour="Masked"))  
  geom_line(aes(y=NoMask, colour="NoMask"))
  • Related