r 中重叠范围图的图例

legend for overlapping ranges plot in r

我设法根据 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"))

数据框看起来像这样

> 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

我的问题是,是否可以为每个范围设置图例?我想命名蓝色和红色范围以及绿色点。

一个解决方案是在 aes() 中传递颜色,可以使用任何你想要的名称,因为你需要稍后定义它们,就像我在 scale_color_manual

的示例中所做的那样

代码

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"))

输出