Search code examples
rggplot2plotsimulationmontecarlo

Adding a single legend for two horizontal lines in ggplot


I little experience with ggplot2. I am trying to plot coverage probability and cohort size using the code below:

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)

I have three questions: 1. When I run the code, I get a warning; how can I fix it. 2. There are two horizontal black dashed lines and I want to have just one legend for both to represent '95% CL'. 3. I feel the code is too much, is there a much simpler way of writing it using ggplot2 only.

Thanks!!


Solution

  • I can't install latex2exp. Without this package, you simply can try this and in my opinion all three questions are solved:

    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)
    

    enter image description here