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 <noreply@anthropic.com>
This commit is contained in:
jaredandClaude Sonnet 5.5 committed 2026-10-15 15:27:55 -04:00
1 parent d6e3ba2fb4
commit 0561df4221
6 files changed
+171 -72

No files matched your search

+1
View File
@@ -34,6 +34,7 @@ Suggests:
quarto, quarto,
flextable, flextable,
officer, officer,
patchwork,
ragg ragg
Config/testthat/edition: 3 Config/testthat/edition: 3
Config/roxygen2/version: 8.0.0 Config/roxygen2/version: 8.0.0
+61 -57
View File
@@ -44,65 +44,67 @@ get_png <- function(filename) {
#' Add a logo to a ggplot2 object #' 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 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 margin_param Optional numeric. Replaces the plot margin (in points)
#' @param font_scale Numeric. Multiplicative scaling factor applied to text #' on the side next to the logo. `NULL` (default) leaves the plot's margins
#' sizes before composing the plot with the logo. Default `1.1` inflates #' alone.
#' text by ~10 \% to compensate for the viewport shrinkage caused by #' @param font_scale Numeric. Multiplicative scaling factor applied to the
#' [gridExtra::arrangeGrob()]. Set to `1` to disable. #' base text size before composing. Default `1` leaves typography unchanged.
#' @param position Character. Corner placement for the logo: `"bottom-right"` #' @param position Character. Corner placement for the logo: `"bottom-right"`
#' (default), `"bottom-left"`, `"top-right"`, or `"top-left"`. Controls #' (default), `"bottom-left"`, `"top-right"`, or `"top-left"`. Controls
#' whether the logo is placed above or below the plot. #' 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 #' @return a grob with a logo attached to it ready to plot
#' @importFrom ggplot2 theme #' @importFrom ggplot2 theme
#' @importFrom gridExtra arrangeGrob #' @importFrom gridExtra arrangeGrob
#' @export #' @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", position = c("bottom-right", "bottom-left",
"top-right", "top-left")) { "top-right", "top-left"),
logo_height = 0.5) {
position <- match.arg(position) position <- match.arg(position)
at_top <- grepl("top", position) at_top <- grepl("top", position)
is_patchwork <- inherits(plot, "patchwork")
# Capture the plot's background color so we can fill the entire composed # 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 # grob with it. The logo grob stays transparent (theme_void).
# caption/axis text overlapping via negative margins remains visible.
bg_fill <- plot$theme$plot.background$fill 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) { if (!is.null(font_scale) && font_scale != 1) {
base_size <- plot$theme$text$size %||% 14 base_size <- plot$theme$text$size
plot <- plot + theme( if (is.null(base_size)) base_size <- 14
text = element_text(size = base_size * font_scale) scaled <- theme(text = ggplot2::element_text(size = base_size * font_scale))
) plot <- if (is_patchwork) plot & scaled else plot + scaled
} }
if (at_top) { if (!is.null(margin_param)) {
# For top placement, tighten the top margin of the plot side <- if (at_top) c(margin_param, 7, 7, 7) else c(7, 7, margin_param, 7)
if (!is.null(margin_param)) { margin <- theme(plot.margin = grid::unit(side, "pt"))
plot <- plot + theme(plot.margin = unit(c(margin_param, 7, 7, 7), "pt")) plot <- if (is_patchwork) plot & margin else plot + margin
} else { }
plot <- plot + theme(plot.margin = unit(c(-14, 7, 7, 7), "pt"))
} # ggplot_build() on a patchwork builds only its last panel, so convert it
composed <- arrangeGrob(logo, plot, heights = c(0.1, 0.93), # explicitly before handing it to arrangeGrob().
padding = unit(0.1, "line")) 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 { } else {
# Bottom placement (original behaviour) arrangeGrob(plot_grob, logo,
if(has_caption(plot)) { heights = grid::unit.c(plot_height, band_height),
cap_lines <- measure_caption(plot) padding = grid::unit(0.1, "line"))
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"))
} }
# Wrap with a full-bleed background rect so any transparent areas (the # 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 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 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 #' @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 #' @return a grid object
#' @note The resulting object needs to be drawn to the screen using grid.draw() #' @note The resulting object needs to be drawn to the screen using grid.draw()
@@ -179,7 +181,7 @@ has_caption <- function(gg) {
#' dev.off() #' dev.off()
#' } #' }
add_logo_ga <- function(plot_list, logo, nrow = 1, widths = NULL, 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 # Capture the background color from the first plot
bg_fill <- plot_list[[1]]$theme$plot.background$fill 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) align_left <- grepl("left", position)
if (align_left) { # Give the raster a height only, so grid derives its width from the image's
xmin <- 0 # own aspect ratio, then pin it to the corner. The logo is the same shape on
xmax <- if (type == "mark") 0.07 else 0.35 # any canvas width.
} else { logo <- grid::rasterGrob(
xmin <- if (type == "mark") 0.93 else 0.65 png::readPNG(system.file("img", img_file, package = "civilytics")),
xmax <- 1 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() + ggplot() +
theme_void() + theme_void() +
annotation_custom( annotation_custom(logo, xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf)
get_png(system.file("img", img_file, package = "civilytics")),
xmin = xmin, xmax = xmax
)
} }
#' Add a Civilytics logo to a ggplot (pipe-friendly) #' 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"`. #' (default), `"bottom-left"`, `"top-right"`, or `"top-left"`.
#' @param margin_param Numeric or `NULL`. Manual margin adjustment passed to #' @param margin_param Numeric or `NULL`. Manual margin adjustment passed to
#' [add_logo()]. #' [add_logo()].
#' @param font_scale Numeric. Inflate text sizes by this factor to compensate #' @param font_scale Numeric. Multiplies the plot's base text size before
#' for viewport shrinkage when composing with [gridExtra::arrangeGrob()]. #' composing. Default `1` leaves typography unchanged.
#' Default `1.1` (~10 \% inflation). Set to `1` to disable. #' @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 #' @return A grob (from [gridExtra::arrangeGrob()]) ready to draw with
#' [grid::grid.draw()]. #' [grid::grid.draw()].
@@ -355,11 +358,12 @@ civilytics_logo <- function(plot,
position = c("bottom-right", "bottom-left", position = c("bottom-right", "bottom-left",
"top-right", "top-left"), "top-right", "top-left"),
margin_param = NULL, margin_param = NULL,
font_scale = 1.1) { font_scale = 1,
logo_height = 0.5) {
position <- match.arg(position) position <- match.arg(position)
logo <- make_logo_grob(type = type, variant = variant, position = position) logo <- make_logo_grob(type = type, variant = variant, position = position)
add_logo(plot, logo, margin_param = margin_param, font_scale = font_scale, add_logo(plot, logo, margin_param = margin_param, font_scale = font_scale,
position = position) position = position, logo_height = logo_height)
} }
+17 -9
View File
@@ -8,29 +8,37 @@ add_logo(
plot, plot,
logo, logo,
margin_param = NULL, margin_param = NULL,
font_scale = 1.1, font_scale = 1,
position = c("bottom-right", "bottom-left", "top-right", "top-left") position = c("bottom-right", "bottom-left", "top-right", "top-left"),
logo_height = 0.5
) )
} }
\arguments{ \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{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 \item{font_scale}{Numeric. Multiplicative scaling factor applied to the
sizes before composing the plot with the logo. Default `1.1` inflates base text size before composing. Default `1` leaves typography unchanged.}
text by ~10 \% to compensate for the viewport shrinkage caused by
[gridExtra::arrangeGrob()]. Set to `1` to disable.}
\item{position}{Character. Corner placement for the logo: `"bottom-right"` \item{position}{Character. Corner placement for the logo: `"bottom-right"`
(default), `"bottom-left"`, `"top-right"`, or `"top-left"`. Controls (default), `"bottom-left"`, `"top-right"`, or `"top-left"`. Controls
whether the logo is placed above or below the plot.} 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{ \value{
a grob with a logo attached to it ready to plot a grob with a logo attached to it ready to plot
} }
\description{ \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.
} }
+2 -2
View File
@@ -10,7 +10,7 @@ add_logo_ga(
nrow = 1, nrow = 1,
widths = NULL, widths = NULL,
margin_param = NULL, margin_param = NULL,
font_scale = 1.1 font_scale = 1
) )
} }
\arguments{ \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{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 \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{ \value{
a grid object a grid object
+7 -4
View File
@@ -10,7 +10,8 @@ civilytics_logo(
variant = c("light", "dark"), variant = c("light", "dark"),
position = c("bottom-right", "bottom-left", "top-right", "top-left"), position = c("bottom-right", "bottom-left", "top-right", "top-left"),
margin_param = NULL, margin_param = NULL,
font_scale = 1.1 font_scale = 1,
logo_height = 0.5
) )
} }
\arguments{ \arguments{
@@ -28,9 +29,11 @@ civilytics_logo(
\item{margin_param}{Numeric or `NULL`. Manual margin adjustment passed to \item{margin_param}{Numeric or `NULL`. Manual margin adjustment passed to
[add_logo()].} [add_logo()].}
\item{font_scale}{Numeric. Inflate text sizes by this factor to compensate \item{font_scale}{Numeric. Multiplies the plot's base text size before
for viewport shrinkage when composing with [gridExtra::arrangeGrob()]. composing. Default `1` leaves typography unchanged.}
Default `1.1` (~10 \% inflation). Set to `1` to disable.}
\item{logo_height}{Numeric. Height in inches of the band reserved for the
logo. Default `0.5`.}
} }
\value{ \value{
A grob (from [gridExtra::arrangeGrob()]) ready to draw with A grob (from [gridExtra::arrangeGrob()]) ready to draw with
+83
View File
@@ -28,3 +28,86 @@ test_that("stamp_logo_png validates its inputs", {
# invalid type is rejected by match.arg() before the file is touched # invalid type is rejected by match.arg() before the file is touched
expect_error(stamp_logo_png(tempfile(fileext = ".png"), type = "banner")) 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)
}
})