R/ggsubt.R

Defines functions ggsubt

#' ## [**`ggsubt`**][^ggsubt] (Subtitles for `{ggplot2}`, by Bob Rudis)
#'
#'
#' [^ggsubt]: \rurl{https://rud.is/b/2016/03/16/supreme-annotations/}
#'
#'
library(grid)
library(gtable)
ggsubt <-
    function(gg,
             label = "",
             fontfamily = NULL,
             fontsize = 10,
             hjust = 0,
             vjust = 0,
             bottom_margin = 5.5,
             newpage = is.null(vp),
             vp = NULL,
             ...) {
        ## Function to add subtitles to 'ggplot()' ##
        if (is.null(fontfamily)) {
            gpr <- gpar(fontsize = fontsize, ...)
        }
        else {
            gpr <- gpar(fontfamily = fontfamily, fontsize = fontsize, ...)
        }
        subtitle <-
            textGrob(
                label,
                x = unit(hjust, "npc"),
                y = unit(hjust, "npc"),
                hjust = hjust,
                vjust = vjust,
                gp = gpr
            )
        data <- ggplot_build(gg)
        gt <- ggplot_gtable(data)
        gt <- gtable_add_rows(gt, grobHeight(subtitle), 2)
        gt <-
            gtable_add_grob(gt, subtitle, 3, 4, 3, 4, 8, "off", "subtitle")
        gt <-
            gtable_add_rows(gt, grid::unit(bottom_margin, "pt"), 3)
        if (newpage)
            grid.newpage()
        if (is.null(vp)) {
            grid.draw(gt)
        }
        else {
            if (is.character(vp))
                seekViewport(vp)
            else
                pushViewport(vp)
            grid.draw(gt)
            upViewport()
        }
        invisible(data)
    }
#'
EccRiley/Riley documentation built on April 24, 2018, 3:28 a.m.