How to add labels at the top of vlines in ggplot2 and add these in separate legends

166 views Asked by At

I have created a dummy dataframe representative of my data-

SQ     AgeGroup       Prop    LCI      UCI
2010-1  0 to 18        4.3    4.2      4.4
2010-1  19 to 25       5.6    5.3      5.6
2010-1  26 and over    7.8    7.6      7.9
2010-2  0 to 18        4.1    3.9      4.2
2010-2  19 to 25       5.8    5.6      5.9
2010-2  26 and over    8.1    7.9      8.3
2010-3  0 to 18        4.2     4       4.4
2010-3  19 to 25       5.5    5.2      5.6
2010-3  26 and over    7.6    7.4      7.7
2010-4  0 to 18        3.9    3.6      4.1
2010-4  19 to 25       5.2    5        5.4
2010-4  26 and over    7.4    7.2      7.6
2011-1  0 to 18        4.3    4.1      4.5
2011-1  19 to 25       5.7    5.5      5.8
2011-1  26 and over    8.2    8        8.3
2011-2  0 to 18        4.1    4        4.5
2011-2  19 to 25       5.7    5.5      5.9
2011-2  26 and over    8.2    8        8.4
2011-3  0 to 18        4.4    4.2      4.6
2011-3  19 to 25       5.7    5.5      7.9
2011-3  26 and over    8.2    8        8.4

which creates an image that looks like this- enter image description here

I have used the following code-

library(readxl)
library(dplyr)
library(epitools)
library(gtools)
library(reshape2)
library(binom)
library(pivottabler)
library(readxl)
library(phecharts)
library(ggplot2)
library(RODBC)
rm(list=ls())

df<-read_xlsx("Dummydata.xlsx")

pd<-position_dodge(width=0.3)
limits <- aes(ymax =df$UCI , ymin = df$LCI)
p<-ggplot(df, aes(x = SQ, y =Prop, group=AgeGroup, colour= AgeGroup)) +
  geom_line(position=pd)+
  geom_point(size=2.0, position=pd)+
  geom_errorbar(limits, width = 0.55, size=0.4, position= pd)+
  labs(
    y = "Percentage",
    x = "Study Quarter")


p<-p + 

  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))+
  scale_y_continuous(name="Percentage",breaks=c(0,2,4,6,8,10),limits=c(0,10))+#limits need to change with every pot

  scale_fill_manual(values = pal)+
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1,size=16))+
  theme(axis.text.y=element_text(size=16))+
  theme(legend.text = element_text(size=18))+

  theme(legend.title=element_text(size=16))+
  theme(legend.title=element_blank())+
  theme(legend.position="bottom")+
  theme(axis.title = element_text(size=22))



p + geom_vline(xintercept = c(2,4,6), linetype="dotted", 
               color = "black", size=1.0, show.legend = TRUE)

However, what I want is that the three geom lines should have a lable (L1, L2 and L3) at the top of each of these lines and a separate legend at the bottom where I can add what these lines stand for. Something like this-

L1: Launch of x
L2: Launch of y
L3: Launch of z

Can someone please help with this?

0

There are 0 answers