Skip to content

Patches with an inset do not get tagged when ignore_tags=TRUE. #416

Open
@trekonom

Description

@trekonom

Happy new year @thomasp85 !

I stumbled over this issue based on this SO post. As documented there, tagging fails when creating a patch of multiple plots containing an inset element each.

Using the (slightly modified) code from the SO post the second plot in the top row does not get tagged:

library(ggplot2)
library(patchwork)

packageVersion("ggplot2")
#> [1] '3.5.1'
packageVersion("patchwork")
#> [1] '1.3.0'

p1 <- ggplot(mtcars) +
  geom_point(aes(mpg, disp)) +
  ggtitle("Plot 1")

p2 <- ggplot(mtcars) +
  geom_boxplot(aes(gear, disp, group = gear)) +
  ggtitle("Plot 2")

p3 <- ggplot(mtcars) +
  geom_point(aes(hp, wt, colour = mpg)) +
  ggtitle("Plot 3")

p4 <- ggplot(mtcars) +
  geom_bar(aes(gear)) +
  labs(x = NULL, y = NULL, title = "Plot 4")

inset <- inset_element(
  p4, 0, 0, 0.6, 0.6,
  ignore_tag = TRUE
)

((p1 + inset) + (p2 + inset)) / p3 +
  plot_annotation(tag_levels = "A")

Created on 2025-01-04 with reprex v2.1.1

Additionally, when using wrap_plots() to create the top row of the patch neither of the top row plots gets tagged:

wrap_plots(p1 + inset, p2 + inset) / p3 +
  plot_annotation(tag_levels = "A")

Created on 2025-01-04 with reprex v2.1.1

I had a look at the underlying issue. From my understanding the issue is that a patch with an inset (with ignore_tag = TRUE) does not get tagged as it gets skipped in recurse_tags:

if (is_inset_patch(patches[[i]]) && !has_tag(patches[[i]])) {
next
}
)

A possible fix would be to simply drop this check as is should already been accounted for in

} else if (has_tag(patches[[i]])) {
, i.e. after dropping lines 122-124 we get the desired result (and all tests still pass):

((p1 + inset) + (p2 + inset)) / p3 +
  plot_annotation(tag_levels = "A")

wrap_plots(p1 + inset, p2 + inset) / p3 +
  plot_annotation(tag_levels = "A")

And it still works for the "examples":

# Tagging also continues to work as expected
p1 +
  inset_element(p2, 0.6, 0.6, 1, 1) +
  plot_annotation(tag_levels = "1")

# but can be turned off, like for wrapped plots
p1 +
  inset_element(p2, 0.6, 0.6, 1, 1, ignore_tag = TRUE) +
  plot_annotation(tag_levels = "1")

Created on 2025-01-04 with reprex v2.1.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions