legend for overlapping ranges plot in r

Viewed 110

I managed to create following ranges plot based on solution presented in post: Plot 'ranges' of variable in data .

library(ggplot2)

r <- c("r1","r2","r3")
s_lb <- c(2,3,1)
s_ub <- c(3,5,3)
FVA_lb <- c(1,1,0)
FVA_ub <- c(5,6,4)
lmoma <- c(2,4,2)
d <- data.frame(reaction=r, smin=s_lb, smax=s_ub, fmin=FVA_lb, fmax=FVA_ub, lmoma=lmoma)

p <- ggplot(d, aes(x=reaction))+
  geom_linerange(aes(ymin=fmin,ymax=fmax),linetype=1,color="blue",size=2)+
  geom_point(aes(y=fmin),size=3,color="blue")+
  geom_point(aes(y=fmax),size=3,color="blue")+
  geom_linerange(aes(ymin=smin,ymax=smax),linetype=1,color="red",size=2)+
  theme(legend.position = "bottom")+
  geom_point(aes(y=smin),size=3,color="red")+
  geom_point(aes(y=smax),size=3,color="red")+
  geom_point(aes(y=lmoma),size=3,color="green")+
  labs(title = "All")+
  ylab("Range [mmol*gDW-1*hr-1]")+
  xlab("Reaction")+
  theme(panel.grid.major = element_line(colour = "grey"), axis.text.x = element_text(angle = 90),plot.title = element_text(hjust = 0.5),panel.background = element_rect(fill = "lightgrey"))

The data frame looks like that

> d
  reaction smin smax fmin fmax lmoma
1       r1    2    3    1    5     2
2       r2    3    5    1    6     4
3       r3    1    3    0    4     2

My question is, is it possible to set legend for every range? I would like to name the blue and red ranges and green points. enter image description here

1 Answers

A solution is to pass the color inside aes(), with any name you want, because you need to define them later, as I did in the example with scale_color_manual

Code

ggplot(d, aes(x=reaction))+
  geom_linerange(aes(ymin=fmin,ymax=fmax,color="blue"),linetype=1,size=2)+
  geom_point(aes(y=fmin,color="blue"),size=3)+
  geom_point(aes(y=fmax,color="blue"),size=3)+
  geom_linerange(aes(ymin=smin,ymax=smax,color="red"),linetype=1,size=2)+
  theme(legend.position = "bottom")+
  geom_point(aes(y=smin,color="red"),size=3)+
  geom_point(aes(y=smax,color="red"),size=3)+
  geom_point(aes(y=lmoma,color="green"),size=3)+
  labs(title = "All")+
  ylab("Range [mmol*gDW-1*hr-1]")+
  xlab("Reaction")+
  theme(panel.grid.major = element_line(colour = "grey"), axis.text.x = element_text(angle = 90),plot.title = element_text(hjust = 0.5),panel.background = element_rect(fill = "lightgrey"))+
  scale_color_manual(values = c("blue","green","red"))

Output

enter image description here

Related