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?
CodePudding user response:
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)))
CodePudding user response:
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)))