在ggplot中为两条水平线添加一个图例

Adding a single legend for two horizontal lines in ggplot

我对 ggplot2 经验不多。我正在尝试使用以下代码绘制覆盖概率和队列大小:

library("reshape2")
library("ggplot2")
library(latex2exp)
CP1 <-c(0.953,0.942,0.947,0.958)
CP2 <- c(0.937,0.952,0.955,0.957)
cohort <- c(500,1000,5000,10000)
mdata <- data.frame(rate1=CP1,rate2=CP2,cohort.size=cohort)

mydata <- melt(mdata,id='cohort.size',value.name="CP")
ggplot(mydata , aes(x=cohort.size, y=CP)) +
  geom_line(size=1,aes(colour=variable)) +
  geom_point( size=4, shape=0)+ coord_cartesian(ylim = c(0,1)) +
  scale_x_continuous(breaks=c(500,1000,5000,10000))+
  scale_color_discrete(labels = unname(TeX(c(" $\r_1$", "$\r_2$")))) +
  geom_hline(yintercept =c(0.936,0.964) ,linetype="dashed") + 

  theme(legend.title = element_blank(), axis.title.x = element_text(color="#993333", size=14, face="bold"), 
        axis.title.y = element_text(color="#993333", size=14, face="bold"),
        plot.title = element_text(color="#993333", size=14, face="bold"),
        legend.position = c(.85, .85),
        legend.justification = c("right", "top"),
        legend.box.just = "right",
        legend.margin = margin(6, 6, 6, 6),legend.text=element_text(size=20)) + xlab("Cohort Size") + ylab("Coverage Proability")+

  annotate("text",
           x = 8700,
           y = 0.68, 
           label =expression(bold(paste("MN=57% \n AB=38% \n XYZ=5%" ))),parse = TRUE,size=5)

我有三个问题: 1. 当我 运行 代码时,我得到一个警告;我该如何解决。 2. 有两条水平 black 虚线,我只想用一个图例来代表“95% CL”。 3.感觉代码太多了,有没有更简单的只用ggplot2写的方法。

谢谢!!

我无法安装 latex2exp。没有这个包,你可以试试这个,我认为这三个问题都解决了:

ggplot(mydata , aes(x=cohort.size, y=CP)) + 
  geom_line(size=1,aes(colour=variable)) +
  geom_point( size=4, shape=0)+ 
  geom_hline(data = data.frame(yintercept =c(0.936,0.964)),
             aes(yintercept =yintercept, linetype ='95% CL')) +
  scale_linetype_manual("", values = 2) +
  ylim(0,1) +
  annotate("text",
           x = 8700,
           y = 0.68, 
           label = paste("MN=57%\n AB=38%\n XYZ=5%" ),
           size=5, fontface =2)