0

Below is the sample data. Trying to have two lines with different colors. Seems pretty simple but running into the below error. Have two questions. First, how do I get around this error. Second, how would I edit the legend to where it says "Hires" instead of "HI".

 "geom_path: Each group consists of only one observation. Do you need to

adjust the group aesthetic?"

 library(ggplot2)


 measure <- c("HI","HI","HI","HI","HI","JO","JO","JO","JO","JO")
 date <- c("2002-01","2002-02","2002-03","2002-04","2002-05","2002-01","2002-02","2002-03","2002-04","2002-05")
 value <- c(100,105,95,145,110,25,35,82,75,90)

 df <- data.frame(measure,date,value)

  graph <- df %>% ggplot (aes(x=date, y= value, color = measure)) + geom_line () + theme (legend.position = "bottom",legend.title = element_blank())

  print(graph)
Tim Wilcox
  • 1,275
  • 2
  • 19
  • 43

1 Answers1

2

It's asking for a group, so you can give it a group:

ggplot(aes(x=date, y=value, group=measure, color=measure))

It's a bit surprising that it's not already grouped, and I'm not exactly sure why, but the above change appears to produce the result you want:

If you're interested in why it's asking for a group, I'd recommend simplifying and reformatting your example, and then asking as a separate question.

Dommondke
  • 307
  • 1
  • 8
  • 1
    The issue is that `ggplot2` groups by all (!!) categorical variables. And as `date` is a character aka categorical it tries to make a line per date-measure pair. Hence only one obs per group. That's the reason why we need to set the `group` aes. – stefan Jun 28 '22 at 21:16
  • 1
    @stefan Ah, weird. I never noticed that before. I tried doing `as.factor` on `date` and `measure` but it didn't help – Dommondke Jun 28 '22 at 21:20
  • And thank you for the upvote, now I can actually embed the image :) – Dommondke Jun 28 '22 at 21:22
  • Haha. When I started with ggplot2 this made me crazy before I learned about the `group` aes. +1 – stefan Jun 28 '22 at 21:22