如何在ggplot2中添加hline图例

Rob*_*bin 2 r ggplot2

我的数据如下所示:

month=c("Jan","Feb","Mar","Apr","May","Jun")
rate=c(70,80,90,85,88,76) 
dd=data.frame(month,rate)
dd$type="Rate"
dd$month=factor(dd$month)
Run Code Online (Sandbox Code Playgroud)

我尝试创建这样的情节:

ggplot(dd,aes(x=month,y=rate,color=type)) + 
  geom_point(aes(x=month,y=rate, group=1), size=2) +
  geom_text(aes(label = paste(format(rate, digits = 4, format = "f"), "%")), 
            color="black",vjust = -0.5, size = 3.5) +
  geom_line(aes(x = month, y = rate, group=1), size=1) + 
  geom_hline(aes(yintercept=85), linetype='dashed',colour="#F8766D", show.legend=T) +
  labs(y="", x="") + 
  scale_colour_manual(values = c("#00BFC4")) +
  scale_fill_discrete(limits = c("Target")) +
  theme(legend.position="bottom") +
  theme(legend.title = element_blank()) 
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

正如您所看到的,速率和目标的图例重叠在一起(绿线中有红色虚线),我想知道如何以正确的方式创建目标和速率的图例。谢谢!

ste*_*fan 6

实现所需结果的一种选择是映射美学并使用scale_xxx_manual而不是通过参数设置颜色、线型等:

month=c("Jan","Feb","Mar","Apr","May","Jun")
rate=c(70,80,90,85,88,76) 
dd=data.frame(month,rate)
dd$type="Rate"
dd$month=factor(dd$month)

library(ggplot2)

ggplot(dd,aes(x=month,y=rate, color="Rate", linetype = "Rate")) + 
  geom_point(aes(x=month,y=rate, shape = "Rate"), size=2) +
  geom_text(aes(label = paste(format(rate, digits = 4, format = "f"), "%")), 
            color="black",vjust = -0.5, size = 3.5) +
  geom_line(aes(x = month, y = rate, group=1, size = "Rate")) + 
  geom_hline(aes(yintercept=85, color = "Target", linetype = "Target", size = "Target")) +
  labs(y = NULL, x= NULL, color = NULL, linetype = NULL, shape = NULL, size = NULL) + 
  scale_colour_manual(values = c(Rate = "#00BFC4", Target = "#F8766D")) +
  scale_linetype_manual(values = c(Rate = "solid", Target = "dashed")) +
  scale_shape_manual(values = c(Rate = 16, Target = NA)) +
  scale_size_manual(values = c(Rate = 1, Target = .5)) +
  theme(legend.position="bottom")
Run Code Online (Sandbox Code Playgroud)