如何在ggplot2中的vlines顶部添加标签并将其添加到单独的图例中

时间:2018-09-18 17:24:51

标签: r ggplot2 geom-vline

我已经创建了一个代表我的数据的虚拟数据框-

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

创建一个看起来像这样的图像- enter image description here

我使用了以下代码-

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)

但是,我想要的是这三个geom行应该在每行的顶部都有一个标签(L1,L2和L3),并在底部有一个单独的图例,我可以在其中添加这些行的含义。像这样的东西-

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

有人可以帮忙吗?

0 个答案:

没有答案