From 0561df42212825f805297551f9616b52dc84b69c Mon Sep 17 00:00:00 2001 From: Jared Knowles Date: Thu, 15 Oct 2026 15:27:55 -0400 Subject: [PATCH] fix(logo): reserve a logo band, keep patchwork panels, and preserve logo aspect (#20) The logo gets its own band (logo_height inches) instead of negative margins, so captions are no longer clipped. Patchwork compositions go through patchworkGrob() so every panel survives. font_scale defaults to 1. make_logo_grob() sizes by height so the logo keeps its shape on any canvas. Closes #20 Co-Authored-By: Claude Sonnet 5.5 --- DESCRIPTION | 1 + R/logo.R | 118 +++++++++++++++++++------------------ man/add_logo.Rd | 26 +++++--- man/add_logo_ga.Rd | 4 +- man/civilytics_logo.Rd | 11 ++-- tests/testthat/test_logo.R | 83 ++++++++++++++++++++++++++ 6 files changed, 171 insertions(+), 72 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index b962e0f..4f6f6b2 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -34,6 +34,7 @@ Suggests: quarto, flextable, officer, + patchwork, ragg Config/testthat/edition: 3 Config/roxygen2/version: 8.0.0 diff --git a/R/logo.R b/R/logo.R index 2508cb5..9f28b4b 100644 --- a/R/logo.R +++ b/R/logo.R @@ -44,65 +44,67 @@ get_png <- function(filename) { #' Add a logo to a ggplot2 object #' -#' @param plot a ggplot2 grob +#' The logo gets its own band of reserved height (`logo_height`, in inches) +#' below or above the plot, so it cannot overlap the plot's caption or push +#' anything off the canvas. Patchwork compositions are converted with +#' [patchwork::patchworkGrob()] so every panel and the +#' [patchwork::plot_annotation()] survive. +#' +#' @param plot a ggplot2 object, or a patchwork composition #' @param logo a logo grob created by make_logo_grob() -#' @param margin_param a numeric specifying what margin to add or subtract to align the logo -#' @param font_scale Numeric. Multiplicative scaling factor applied to text -#' sizes before composing the plot with the logo. Default `1.1` inflates -#' text by ~10 \% to compensate for the viewport shrinkage caused by -#' [gridExtra::arrangeGrob()]. Set to `1` to disable. +#' @param margin_param Optional numeric. Replaces the plot margin (in points) +#' on the side next to the logo. `NULL` (default) leaves the plot's margins +#' alone. +#' @param font_scale Numeric. Multiplicative scaling factor applied to the +#' base text size before composing. Default `1` leaves typography unchanged. #' @param position Character. Corner placement for the logo: `"bottom-right"` #' (default), `"bottom-left"`, `"top-right"`, or `"top-left"`. Controls #' whether the logo is placed above or below the plot. +#' @param logo_height Numeric. Height in inches of the band reserved for the +#' logo. Default `0.5`. #' #' @return a grob with a logo attached to it ready to plot #' @importFrom ggplot2 theme #' @importFrom gridExtra arrangeGrob #' @export -add_logo <- function(plot, logo, margin_param = NULL, font_scale = 1.1, +add_logo <- function(plot, logo, margin_param = NULL, font_scale = 1, position = c("bottom-right", "bottom-left", - "top-right", "top-left")) { + "top-right", "top-left"), + logo_height = 0.5) { position <- match.arg(position) at_top <- grepl("top", position) + is_patchwork <- inherits(plot, "patchwork") # Capture the plot's background color so we can fill the entire composed - # grob with it. The logo grob must stay transparent (theme_void) so that - # caption/axis text overlapping via negative margins remains visible. + # grob with it. The logo grob stays transparent (theme_void). bg_fill <- plot$theme$plot.background$fill - # Inflate text sizes to compensate for arrangeGrob viewport shrinkage. - # All theme text elements use rel() sizing, so scaling the root 'text' - # element cascades to titles, axis labels, legends, captions, and strips. if (!is.null(font_scale) && font_scale != 1) { - base_size <- plot$theme$text$size %||% 14 - plot <- plot + theme( - text = element_text(size = base_size * font_scale) - ) + base_size <- plot$theme$text$size + if (is.null(base_size)) base_size <- 14 + scaled <- theme(text = ggplot2::element_text(size = base_size * font_scale)) + plot <- if (is_patchwork) plot & scaled else plot + scaled } - if (at_top) { - # For top placement, tighten the top margin of the plot - if (!is.null(margin_param)) { - plot <- plot + theme(plot.margin = unit(c(margin_param, 7, 7, 7), "pt")) - } else { - plot <- plot + theme(plot.margin = unit(c(-14, 7, 7, 7), "pt")) - } - composed <- arrangeGrob(logo, plot, heights = c(0.1, 0.93), - padding = unit(0.1, "line")) + if (!is.null(margin_param)) { + side <- if (at_top) c(margin_param, 7, 7, 7) else c(7, 7, margin_param, 7) + margin <- theme(plot.margin = grid::unit(side, "pt")) + plot <- if (is_patchwork) plot & margin else plot + margin + } + + # ggplot_build() on a patchwork builds only its last panel, so convert it + # explicitly before handing it to arrangeGrob(). + plot_grob <- if (is_patchwork) patchwork::patchworkGrob(plot) else plot + + plot_height <- grid::unit(1, "null") + band_height <- grid::unit(logo_height, "in") + composed <- if (at_top) { + arrangeGrob(logo, plot_grob, heights = grid::unit.c(band_height, plot_height), + padding = grid::unit(0.1, "line")) } else { - # Bottom placement (original behaviour) - if(has_caption(plot)) { - cap_lines <- measure_caption(plot) - if (!is.null(margin_param)) { - plot <- plot + theme(plot.margin = unit(c(7, 7, margin_param, 7), "pt")) - } else { - plot <- plot + theme(plot.margin = unit(c(7, 7, cap_lines * -52, 7), "pt")) - } - } else { - plot <- plot + theme(plot.margin = unit(c(7, 7, -14, 7), "pt")) - } - composed <- arrangeGrob(plot, logo, heights = c(0.93, 0.1), - padding = unit(0.1, "line")) + arrangeGrob(plot_grob, logo, + heights = grid::unit.c(plot_height, band_height), + padding = grid::unit(0.1, "line")) } # Wrap with a full-bleed background rect so any transparent areas (the @@ -160,7 +162,7 @@ has_caption <- function(gg) { #' @param widths an optional vector the same length as plot_list with the widths for each plot #' @param margin_param a number giving the adjustment up or down to help manually align logo and captions #' @param font_scale Numeric. Multiplicative scaling factor applied to text -#' sizes before composing. Default `1.1`. See [add_logo()] for details. +#' sizes before composing. Default `1`. See [add_logo()] for details. #' #' @return a grid object #' @note The resulting object needs to be drawn to the screen using grid.draw() @@ -179,7 +181,7 @@ has_caption <- function(gg) { #' dev.off() #' } add_logo_ga <- function(plot_list, logo, nrow = 1, widths = NULL, - margin_param = NULL, font_scale = 1.1) { + margin_param = NULL, font_scale = 1) { # Capture the background color from the first plot bg_fill <- plot_list[[1]]$theme$plot.background$fill @@ -268,20 +270,20 @@ make_logo_grob <- function(type = c("wordmark", "mark"), align_left <- grepl("left", position) - if (align_left) { - xmin <- 0 - xmax <- if (type == "mark") 0.07 else 0.35 - } else { - xmin <- if (type == "mark") 0.93 else 0.65 - xmax <- 1 - } + # Give the raster a height only, so grid derives its width from the image's + # own aspect ratio, then pin it to the corner. The logo is the same shape on + # any canvas width. + logo <- grid::rasterGrob( + png::readPNG(system.file("img", img_file, package = "civilytics")), + x = if (align_left) grid::unit(7, "pt") else grid::unit(1, "npc") - grid::unit(7, "pt"), + just = if (align_left) "left" else "right", + height = grid::unit(1, "npc"), + interpolate = TRUE + ) ggplot() + theme_void() + - annotation_custom( - get_png(system.file("img", img_file, package = "civilytics")), - xmin = xmin, xmax = xmax - ) + annotation_custom(logo, xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf) } #' Add a Civilytics logo to a ggplot (pipe-friendly) @@ -308,9 +310,10 @@ make_logo_grob <- function(type = c("wordmark", "mark"), #' (default), `"bottom-left"`, `"top-right"`, or `"top-left"`. #' @param margin_param Numeric or `NULL`. Manual margin adjustment passed to #' [add_logo()]. -#' @param font_scale Numeric. Inflate text sizes by this factor to compensate -#' for viewport shrinkage when composing with [gridExtra::arrangeGrob()]. -#' Default `1.1` (~10 \% inflation). Set to `1` to disable. +#' @param font_scale Numeric. Multiplies the plot's base text size before +#' composing. Default `1` leaves typography unchanged. +#' @param logo_height Numeric. Height in inches of the band reserved for the +#' logo. Default `0.5`. #' #' @return A grob (from [gridExtra::arrangeGrob()]) ready to draw with #' [grid::grid.draw()]. @@ -355,11 +358,12 @@ civilytics_logo <- function(plot, position = c("bottom-right", "bottom-left", "top-right", "top-left"), margin_param = NULL, - font_scale = 1.1) { + font_scale = 1, + logo_height = 0.5) { position <- match.arg(position) logo <- make_logo_grob(type = type, variant = variant, position = position) add_logo(plot, logo, margin_param = margin_param, font_scale = font_scale, - position = position) + position = position, logo_height = logo_height) } diff --git a/man/add_logo.Rd b/man/add_logo.Rd index f7c09a7..5936ffb 100644 --- a/man/add_logo.Rd +++ b/man/add_logo.Rd @@ -8,29 +8,37 @@ add_logo( plot, logo, margin_param = NULL, - font_scale = 1.1, - position = c("bottom-right", "bottom-left", "top-right", "top-left") + font_scale = 1, + position = c("bottom-right", "bottom-left", "top-right", "top-left"), + logo_height = 0.5 ) } \arguments{ -\item{plot}{a ggplot2 grob} +\item{plot}{a ggplot2 object, or a patchwork composition} \item{logo}{a logo grob created by make_logo_grob()} -\item{margin_param}{a numeric specifying what margin to add or subtract to align the logo} +\item{margin_param}{Optional numeric. Replaces the plot margin (in points) +on the side next to the logo. `NULL` (default) leaves the plot's margins +alone.} -\item{font_scale}{Numeric. Multiplicative scaling factor applied to text -sizes before composing the plot with the logo. Default `1.1` inflates -text by ~10 \% to compensate for the viewport shrinkage caused by -[gridExtra::arrangeGrob()]. Set to `1` to disable.} +\item{font_scale}{Numeric. Multiplicative scaling factor applied to the +base text size before composing. Default `1` leaves typography unchanged.} \item{position}{Character. Corner placement for the logo: `"bottom-right"` (default), `"bottom-left"`, `"top-right"`, or `"top-left"`. Controls whether the logo is placed above or below the plot.} + +\item{logo_height}{Numeric. Height in inches of the band reserved for the +logo. Default `0.5`.} } \value{ a grob with a logo attached to it ready to plot } \description{ -Add a logo to a ggplot2 object +The logo gets its own band of reserved height (`logo_height`, in inches) +below or above the plot, so it cannot overlap the plot's caption or push +anything off the canvas. Patchwork compositions are converted with +[patchwork::patchworkGrob()] so every panel and the +[patchwork::plot_annotation()] survive. } diff --git a/man/add_logo_ga.Rd b/man/add_logo_ga.Rd index c065575..9163a01 100644 --- a/man/add_logo_ga.Rd +++ b/man/add_logo_ga.Rd @@ -10,7 +10,7 @@ add_logo_ga( nrow = 1, widths = NULL, margin_param = NULL, - font_scale = 1.1 + font_scale = 1 ) } \arguments{ @@ -25,7 +25,7 @@ add_logo_ga( \item{margin_param}{a number giving the adjustment up or down to help manually align logo and captions} \item{font_scale}{Numeric. Multiplicative scaling factor applied to text -sizes before composing. Default `1.1`. See [add_logo()] for details.} +sizes before composing. Default `1`. See [add_logo()] for details.} } \value{ a grid object diff --git a/man/civilytics_logo.Rd b/man/civilytics_logo.Rd index c09faa8..ad078f2 100644 --- a/man/civilytics_logo.Rd +++ b/man/civilytics_logo.Rd @@ -10,7 +10,8 @@ civilytics_logo( variant = c("light", "dark"), position = c("bottom-right", "bottom-left", "top-right", "top-left"), margin_param = NULL, - font_scale = 1.1 + font_scale = 1, + logo_height = 0.5 ) } \arguments{ @@ -28,9 +29,11 @@ civilytics_logo( \item{margin_param}{Numeric or `NULL`. Manual margin adjustment passed to [add_logo()].} -\item{font_scale}{Numeric. Inflate text sizes by this factor to compensate -for viewport shrinkage when composing with [gridExtra::arrangeGrob()]. -Default `1.1` (~10 \% inflation). Set to `1` to disable.} +\item{font_scale}{Numeric. Multiplies the plot's base text size before +composing. Default `1` leaves typography unchanged.} + +\item{logo_height}{Numeric. Height in inches of the band reserved for the +logo. Default `0.5`.} } \value{ A grob (from [gridExtra::arrangeGrob()]) ready to draw with diff --git a/tests/testthat/test_logo.R b/tests/testthat/test_logo.R index fa7cf08..6483de6 100644 --- a/tests/testthat/test_logo.R +++ b/tests/testthat/test_logo.R @@ -28,3 +28,86 @@ test_that("stamp_logo_png validates its inputs", { # invalid type is rejected by match.arg() before the file is touched expect_error(stamp_logo_png(tempfile(fileext = ".png"), type = "banner")) }) + +# --- civilytics_logo() layout (#20) ------------------------------------------ + +caption_plot <- function() { + ggplot2::ggplot(mtcars, ggplot2::aes(mpg, wt)) + + ggplot2::geom_point() + + ggplot2::labs(title = "Title", + caption = "Source: a reasonably long attribution line, 2021-22\nSecond line") + + theme_civilytics() +} + +# The composed grob is a gtable, wrapped in a grobTree when the plot has a +# background fill. +composed_table <- function(composed) { + if (inherits(composed, "gtable")) composed else composed$children[[2]] +} + +bottom_ink <- function(grob, width, height, rows = 2) { + path <- tempfile(fileext = ".png") + grDevices::png(path, width = width, height = height, units = "in", res = 100) + grid::grid.newpage() + grid::grid.draw(grob) + grDevices::dev.off() + img <- png::readPNG(path) + n <- dim(img)[1] + edge <- img[(n - rows + 1):n, , 1:3, drop = FALSE] + sum(edge < 0.5) +} + +test_that("font_scale defaults to 1 everywhere", { + expect_identical(formals(add_logo)$font_scale, 1) + expect_identical(formals(add_logo_ga)$font_scale, 1) + expect_identical(formals(civilytics_logo)$font_scale, 1) +}) + +test_that("the logo band is reserved space that sums to the canvas", { + p <- caption_plot() + for (pos in c("bottom-right", "top-left")) { + composed <- suppressWarnings(civilytics_logo(p, position = pos, logo_height = 0.6)) + heights <- composed_table(composed)$heights + expect_equal(length(heights), 2) + expect_true(any(grepl("null", as.character(heights)))) + expect_true(any(grepl("0.6", as.character(heights)))) + } +}) + +test_that("a caption is not clipped at the bottom edge at several canvas sizes", { + skip_on_cran() + p <- caption_plot() + for (w in c(8, 11, 16, 24)) { + h <- w * 0.64 + ink <- bottom_ink(suppressWarnings(civilytics_logo(p, position = "top-right")), w, h) + expect_equal(ink, 0, info = paste("width", w)) + } +}) + +test_that("patchwork compositions keep every panel", { + skip_if_not_installed("patchwork") + p1 <- ggplot2::ggplot(mtcars, ggplot2::aes(mpg, wt)) + ggplot2::geom_point() + p2 <- ggplot2::ggplot(mtcars, ggplot2::aes(hp, wt)) + ggplot2::geom_point() + pw <- p1 + p2 + patchwork::plot_annotation(title = "Both panels") + composed <- suppressWarnings(civilytics_logo(pw)) + panel_grob <- composed_table(composed)$grobs[[1]] + n_panels <- sum(grepl("^panel", panel_grob$layout$name)) + expect_gte(n_panels, 2) +}) + +test_that("the logo keeps its aspect ratio at any canvas width (#20)", { + skip_if_not_installed("ragg") + ink_aspect <- function(width, type) { + path <- tempfile(fileext = ".png") + ragg::agg_png(path, width = width, height = 0.5, units = "in", res = 200, + background = "transparent") + grid::grid.draw(ggplot2::ggplotGrob(make_logo_grob(type = type))) + grDevices::dev.off() + ink <- which(png::readPNG(path)[, , 4] > 0.05, arr.ind = TRUE) + diff(range(ink[, 2])) / diff(range(ink[, 1])) + } + for (type in c("wordmark", "mark")) { + aspects <- vapply(c(6, 11, 24), ink_aspect, numeric(1), type = type) + expect_lt(diff(range(aspects)) / mean(aspects), 0.03, label = type) + } +})