如何使用ggplotGrob创建自定义图例?

时间:2015-03-26 18:50:41

标签: r ggplot2

我发布了一个question,关于如何使用与图表中的线条颜色相同的文本创建图例。我已经能够使图例文本与线条具有相同的颜色,但不能对图例进行任何其他格式化。我想在底部有传说,更大,更大胆。此外,还可以在绘图底部添加注释。请参阅下面的示例代码

注意:我编辑了here

找到的函数
require(grid); require(gridExtra); require(ggplot2)
gglabcol <- 
function(plot1, ColourList) 

     {
     g <- ggplotGrob(plot1)

     # legend grobs
     g.b <- g[["grobs"]][[which(g$layout$name=="guide-box")]]
     l <- g.b[["grobs"]][[1]][["grobs"]]

     # get grobs for legend symbols (extract colour)
     lg <- ColourList

     # get grobs for legend labels 
     lb <- l[sapply(l, function(i) grepl("guide.label", i))]

     # get change colour of labels to colour of symbols
     for(i in seq_along(lg)) {

       lb[[i]]$gp$col <-  lg[i]

       g.b[["grobs"]][[1]][["grobs"]][sapply(g.b[["grobs"]][[1]][["grobs"]],
                      function(i) grepl("guide.label", i))][[i]] <- lb[[i]]
       }

     # overwrite original legend
     g[["grobs"]][[which(g$layout$name=="guide-box")]] <- g.b

     grid.draw(g)

     invisible(g)
 }



df1 <- data.frame(
sex = factor(c("Female","Female","Male","Male")),
time = factor(c("Lunch","Dinner","Lunch","Dinner"), levels=c("Lunch","Dinner")),
total_bill = c(13.53, 16.81, 16.24, 17.42))

p1<-ggplot(data=df1, aes(x=time, y=total_bill, group=sex, shape=sex, colour=sex)) + 
geom_line()+
scale_color_manual("sex",values=c("green", "blue"))

ColourList<-c("green", "blue")
p1<-gglabcol(p1, ColourList)



p1<-p1+theme(legend.text = element_text(size = 14, face = 'bold'))+
        theme(legend.position="bottom",legend.title=element_text(size=14))

Footnote<-"Note: Shaded area represents one standard deviation from the mean."

p1<-arrangeGrob(p1, sub = textGrob(Footnote, x = 0, hjust = -0.1, vjust=0.1, gp = gpar(fontface = "italic", fontsize = 10)))

0 个答案:

没有答案