在单个网格中排列图形,表格和图例

时间:2017-07-24 01:53:43

标签: r gridview ggplot2 r-markdown legend

我需要在Word中打印一个图表,底部有一个表格,表示图表中使用的图例。我将3个元素分开,我需要将它们放在一个网格中。

我使用grid.arrange来尝试,但每个元素的大小不同,like here

有一种方法可以将它们放在一起,所以在x轴图表和列表中匹配多年,表格的每一行都匹配图例中的每个标签。?

作为第二个问题,可以将Total行放在图例中吗?

任何帮助都将不胜感激。

我使用的代码:

 VARIABLE<-c("OFERT_PLP","OFERT_TP","OFERT_LIC")
X2007<-as.vector(matrix1) #matrices A-D contain randomly generated NA and numerical values
X2008<-as.vector(matrix2)
X2009<-as.vector(matrix3)
X2010<-as.vector(matrix4)
X2011<-as.vector(matrix5)
X2012<-as.vector(matrix6)
X2013<-as.vector(matrix7)
X2014<-as.vector(matrix8)
X2015<-as.vector(matrix9)
X2016<-as.vector(matrix10)
orden<-c(1,2,3)
ETIQUETA<-c("Pregrado","Postitulo","Postgrado")

df<-as.data.frame(cbind(VARIABLE,X2007,X2008,X2009,X2010,X2011,X2012,X2013,X2014,X2015,X2016,orden,ETIQUETA))

df<-df[,colnames(df)!="ETIQUETA"]
dfm1<-melt(df,id.vars = c("VARIABLE","orden"), variable.name = "ANO", value.name = "VALOR")

dfm <- dfm1  %>% group_by(ANO,VARIABLE,VALOR) %>%
  group_by(ANO) %>%
  mutate(pct = (VALOR / sum(VALOR,na.rm=TRUE)), 
         total=sum(VALOR,na.rm=TRUE),
         cumsum=cumsum(VALOR),
         npos = total-cumsum+0.5*VALOR)

d<-as.data.frame(rbind(df[,paste0("X",anos)],colSums(df[,paste0("X",anos)],na.rm=TRUE)))

p1<-ggplot(dfm, aes(x=ANO, y=VALOR, fill=orden)) + 
  geom_bar(stat="identity")+   geom_line(aes(y=total,group=1,linetype="Total"))+  scale_fill_brewer()

none <- element_blank()
p2 <- p1 + theme_bw()  + 
  scale_x_discrete(labels=anos) +
  labs(panel.grid.major = none, panel.grid.minor = none) + 
  labs(panel.background = none) + 
  labs(panel.border = none) +
  xlab(NULL) + ylab(NULL)+ 
  background_grid(major = "y", minor = "none" )+
  geom_text(aes(label=ifelse(pct==0,"",paste0(sprintf("%1.0f",pct*100),"%")),y=npos), colour="black",size=3)
p3<-p2 + theme(legend.title=none,legend.position = "left",legend.text=element_text(size=5),
               legend.key.height=unit(0.8,"line"), axis.text = element_text(size = 8)) + guides(linetype=FALSE)

legend <- get_legend(p3)
p3<-p3+theme(legend.position = "none")
pg <- ggplotGrob(p3)

mythemegra <- gridExtra::ttheme_default(
  core = list(fg_params=list(cex = 0.8)),
  colhead = list(fg_params=list(cex = 0.8)),
  rowhead = list(fg_params=list(cex = 0.8)),parse = "TRUE")

table<-tableGrob(d,rows = NULL,col=NULL,
                 theme = mythemegra)

blankPlot <- ggplot()+geom_blank(aes(1,1)) + cowplot::theme_nothing()

grid.arrange(arrangeGrob(blankPlot,pg,top=textGrob("Title",gp=gpar(fontsize=12,font=2,col="black"),just = "centre"), 
                         nrow=1,ncol=2,widths = c(1,5)),
             arrangeGrob(legend,table,nrow=1,ncol=2,widths = c(1,4.5)),heights=c(6.5,6.5))

0 个答案:

没有答案