0

Here is my example to plot multiple lines with ggplot. It generates error below

library(ggplot2)
test_df <-data.frame(dates= c('12/12/2011', '12/12/2011', '12/13/2011','12/13/2011'),
                     cat = c('a','b','a','b'), value = c(5,6,8,9))

ggplot(data= test_df, aes(x=dates, y = value, colour = cat)) + geom_line()

Error:

geom_path: Each group consists of only one observation. Do you
need to adjust the group aesthetic?

What am I missing? I used the following example: Stackoverflow

Community
  • 1
  • 1
user1700890
  • 7,144
  • 18
  • 87
  • 183
  • 2
    I think ggplot warns you, that it might misunderstand you because you give it 4 discrete "buckets" each having just one element and you want to plot a line for each bucket, which does not make sense. You could prly heal it by telling ggplot to group by cat (adding `group = cat` in `aes`, or by providing a continous x axis instead of a discrete one (e.g. `x=lubridate::mdy(dates)` again inside `aes`). – lukeA Apr 19 '17 at 23:31

1 Answers1

1

The error arises as dates in test_df is a categorical variable

str(test_df)

'data.frame':   4 obs. of  3 variables:
 $ dates: Factor w/ 2 levels "12/12/2011","12/13/2011": 1 1 2 2
 $ cat  : Factor w/ 2 levels "a","b": 1 2 1 2
 $ value: num  5 6 8 9

This can be easily corrected by changing the class of dates within the ggplot command:

ggplot(test_df, aes(x=as.Date(dates, format="%m/%d/%y"), y=value, colour=cat)) + 
    geom_line()

enter image description here

Adam Quek
  • 6,973
  • 1
  • 17
  • 23