使用带有因子颜色的geom_line和手动添加的行添加图例到ggplot

时间:2017-04-13 11:17:03

标签: r ggplot2 legend

我可以看到有很多类似的问题,但我找不到解决我特定问题的方法。 数据:

    #color variable 
color_var <- vector(mode = "double",length = length(risk_accum$risk))
color_var[color_var== '0']<-NA
color_var[risk_accum$risk<6] <- "green4"
color_var[risk_accum$risk>=6 & risk_accum$risk<12] <- "yellow2"
color_var[risk_accum$risk>=12] <- "red"

#plot of Effective Blight Hours accumulation
ggplot(risk_accum)+ 
  geom_line(aes(x = date, y = risk), color = color_var)+
  scale_y_continuous(name = "EBH accumulation")+
  scale_colour_manual(values=c("green", "yellow", "red"))+
  geom_line(aes(date, y= 12), linetype= "dotted", size = 0.1)+
  theme(axis.title.x = element_blank())

生成图表的代码:

{{1}}

我需要一个传说来解释交通灯系统(红色是危险等)并手动添加阈值风险线。

1 个答案:

答案 0 :(得分:2)

将颜色变量添加到数据集,映射到aes内的变量,然后使用scale_*_identity直接使用颜色。

risk_accum$color_var <- NA
risk_accum$color_var[risk_accum$risk<6] <- "green4"
risk_accum$color_var[risk_accum$risk>=6 & risk_accum$risk<12] <- "yellow2"
risk_accum$color_var[risk_accum$risk>=12] <- "red"


ggplot(risk_accum)+ 
  geom_line(aes(x = date, y = risk, color = color_var)) +
  scale_y_continuous(name = "EBH accumulation")+
  scale_color_identity(guide = 'legend') +
  geom_line(aes(date, y= 12), linetype= "dotted", size = 0.1)+
  theme(axis.title.x = element_blank())

enter image description here

您还可以将阈值添加到图例中:

ggplot(risk_accum)+ 
  geom_line(aes(x = date, y = risk, color = color_var)) +
  geom_line(aes(date, y= 12, linetype = "threshold"), size = 0.1)+
  scale_y_continuous(name = "EBH accumulation")+
  scale_color_identity(guide = 'legend') +
  scale_linetype_manual(values = 2) +
  theme(axis.title.x = element_blank())

enter image description here