1

I tried to draw a ggplot with below data and aesthetics

  library(ggplot2)
  mydata = rbind(data.frame('date' = as.Date(c('2010-01-01', '2011-01-01', '2012-01-01')), var1 = c('A', 'A', 'A'), var2 = c('X', 'X', 'X'), val = c(10, 3, 10)),
            data.frame('date' = as.Date(c('2010-01-01', '2011-01-01', '2012-01-01')), var1 = c('B', 'B', 'B'), var2 = c('X', 'X', 'X'), val = c(10+2, 3+2, 10+2)),
            data.frame('date' = as.Date(c('2010-01-01', '2011-01-01', '2012-01-01')), var1 = c('A', 'A', 'A'), var2 = c('Y', 'Y', 'Y'), val = c(10-2, 3-2, 10-2)),
            data.frame('date' = as.Date(c('2010-01-01', '2011-01-01', '2012-01-01')), var1 = c('B', 'B', 'B'), var2 = c('Y', 'Y', 'Y'), val = c(10+5, 3+5, 10+5)))

ggplot(data = mydata, aes(x = date)) +
    geom_line(aes(y = val, color = var1)) +
    geom_point(aes(y = val, color = var1, shape = var2))

This approach is generating a strange plot. I wanted to draw 4 different lines on same date in x-axis, where var1 to be distinguished by colour and var2 to be distinguished by point shape.

Is there any way to achieve this?

Bogaso
  • 2,838
  • 3
  • 24
  • 54

2 Answers2

2

You need to give geom_line some way to tell which points to connect. color = var1 is all it has, so it is connecting all points with the same var1 values. You want a separate line for each group defined by var1 AND var2, so we combine those and give it to the group aesthetic:

ggplot(data = mydata, aes(x = date)) +
    geom_line(aes(y = val, color = var1, group = paste(var1, var2))) +
    geom_point(aes(y = val, color = var1, shape = var2)) + 
    guides(color = guide_legend(override.aes = list(shape = NA)))

enter image description here

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
  • This is indeed correct. Just one thing though, is it possible to remove the shape information from the legend of `var1`? This is because, the shape information e.g. `circle` is present for both colours viz 'red' and `blue` - so it is a bit misleading – Bogaso Oct 03 '22 at 19:05
  • 1
    Yeah, [here's the FAQ on that](https://stackoverflow.com/a/16529687/903061). I'll edit it in. – Gregor Thomas Oct 03 '22 at 19:24
2

You can move your point and line aesthetic mappings to the global mapping:

ggplot(data = mydata, aes(x = date, y=val, color=var1, shape=var2)) +
  geom_line() +
  geom_point() + 
  # as shown by @Gregor Thomas solution below
  guides(color = guide_legend(override.aes = list(shape = NA)))

global_mapping

langtang
  • 22,248
  • 1
  • 12
  • 27