Eduardo Eduardo - 9 days ago 5
R Question

Legend in not mapping linetype when geom_errorbar is used

Consider the data:

enter code here

group <- rep(c("a", "b"), each=10)
res <- c(sample(20:30,10,T),sample(60:80,10,T) )
sd <- rnorm(20,2)
t <- rep(1:10,2)
df <- data.frame(t=t,group=group, res=res, sd=sd)


From that I want this plot:

ggplot(df, aes(x=t, y=res,
group=group,
colour=group,
shape=group ), linetype="solid")+
geom_point()+
geom_errorbar(aes(ymin=res-sd, ymax=res+sd))+
geom_line(aes(linetype=group))


The problem:
The legend is NOT mapping the aesthetics linetype.
It is doing correctly for shape and colour.

I also tried setting the linetype as overall mapping and linetype="solid" in geom_errorbar, but the result was the same. See code bellow.

ggplot(df, aes(x=t, y=res,
group=group,
colour=group,
shape=group,
linetype=group))+
geom_point()+
geom_errorbar(aes(ymin=res-sd, ymax=res+sd), linetype="solid")+
geom_line()


For obvious reasons I don't want errorbars with different line types.
The reason for this many mappings to the same variable is to make it beautifull on screen and black an white print friendly.

How can I do this plot and have the legend mapping the linetype too?

Answer

Here is one option:

ggplot(df, aes(x=t, y=res, 
               group=group, 
               colour=group, 
               shape=group, 
               linetype=group))+
  geom_point()+
  geom_errorbar(aes(ymin=res-sd, ymax=res+sd, 
                    linetype = NULL)) + #remove the mapping
  geom_line()