ggplot linetype by column

Viewed 223

I have this dataframe

dt <-
  data.frame(
    date = c("2020-05", "2020-05", "2020-05", "2020-05", "2020-06", "2020-06", "2020-06", "2020-06"),
    type = c("a", "a", "b", "b", "a", "a", "b", "b"),
    sub_type = c("aa", "bb", "aa", "bb", "aa", "bb", "aa", "bb"),
    value = c(seq(1:8))
  )

I'd like to create graph from it in ggplot, color should be given by type column, linetype by subtype column. For some reason it wont work

Error: geom_path: If you are using dotted or dashed lines, colour, size and linetype must be constant over the line

ggplot(dt,
  aes(
    x=date, 
    y=value, 
    group=sub_type,
    color=sub_type,
    linetype=type
  )
) +
  # geom_point()+
  geom_line()
1 Answers

The error is telling you that you need to use the same variable for both color and linetype. If you want to use linetype and color for different variables, you need to put as group the interaction of both variables.

ggplot(dt, aes(x = date, y = value, group = interaction(type,sub_type), 
               color = type, linetype = sub_type)) +
       geom_point()+
       geom_line()

enter image description here

Related