Add info ribbon flush to bottom of ggplot

2019-07-13 07:52发布

I want to create a programmatic way of adding a ribbon at the bottom of my ggplot2 plots like Fivethirtyeight does. Their plots usually have their logo and source information at the bottom inside the ribbon, e.g.:

(https://espnfivethirtyeight.files.wordpress.com/2016/03/hickey-goodman-1.png?w=575&h=462)

Here's my addBanner function. It works, except when faceting plots, especially with coord_map, the banner ends up wider than the plot:

enter image description here

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")

标签: r ggplot2
0条回答
登录 后发表回答