我想创建一种在我的ggplot2图底部添加功能区的编程方式,如Fivethirtyeight。他们的情节通常在功能区底部有标识和来源信息,例如:
这是我的addBanner函数。它的工作原理,除了在切面图时,特别是使用coord_map,横幅最终比图更宽:
addBanner<-function(plot, lefttext=NULL, righttext=NULL, plotHeight=20, textsize=10, bannercolor="grey",textcolor="white"){
# Create grobs to add to plot
my_g <-
grobTree(rectGrob(gp=gpar(alpha=1
,fill = bannercolor
, col = bannercolor
#,fill="#b82e3e" #red
#,col= "#b82e3e" #red
#,fill="#999999" #grey
#,col= "#999999" #grey
)
)
, textGrob(lefttext, x=0, hjust=0, gp=gpar(col=textcolor
,fontfamily = "Helvetica"
,fontsize = textsize
,fontface="bold"))
,textGrob(righttext, x=1, hjust=1, gp=gpar(col=textcolor
,fontfamily = "Helvetica"
,fontsize = textsize
,fontface="bold")
)
)
gA <- plot
# Add as a strip along bottom
grid.arrange(gA,my_g, heights=c(plotHeight, 1))
}
# TESTING
library(ggplot2)
library(grid)
library(gridExtra)
crimes <- data.frame(state = tolower(rownames(USArrests)), USArrests)
crimesm <- reshape2::melt(crimes, id = 1)
states_map <- map_data("state")
testPlot<-
ggplot(crimesm, aes(map_id = state)) +
geom_map(aes(fill = value), map = states_map) +
coord_map()+
expand_limits(x = states_map$long, y = states_map$lat) +
facet_wrap( ~ variable)
addBanner(testPlot,lefttext=" Company Name",righttext="Source of Data ",textcolor="white")