Skip to content

Feature request: Modify a ggplot's gtable within a ggplot pipeline #6723

@dmuenz

Description

@dmuenz

I'm trying to write an extension for ggplot2 that lets me add text to a plot's margins. And I want to control exactly where the text appears, e.g. below the x-axis values but above the label, or at the top of the plot but below the title.

But accommodating the new text typically requires manual adjustments, e.g. adding a "\n" before the x-axis label to make room above it, and messing with theme(plot.margin). Instead, I'd like to be able to modify a plot's gtable, adding new rows or columns and placing the text there. That way, space is automatically allocated for the new text. I can even use, e.g. gtable::gtable_add_rows(heights = grid::unit(1, "lines")) to specify that the new row is exactly the right size to fit one line of text, no matter the dimensions of the overall plot.

The catch is that I'd like to do this in a normal ggplot2 pipeline. E.g. if my hypothetical new function is called anno_margin, I'd like to be able to write code like this, where I add anno_margin into a pipeline and can keep adding things after it:

mpg |>
  ggplot(aes(cty, hwy)) +
  geom_point() +
  anno_margin("Hello, world!", side = "t") +
  theme_bw()

Now, I can get a plot's gtable and modify it as desired, but the resulting object is no longer a ggplot and thus knows nothing about the original aesthetic mappings, scales, etc. So I can't add any more layers or other plot elements. Converting the gtable back to a ggplot with patchwork::wrap_ggplot_grob or ggplotify::as.ggplot doesn't help for the same reason -- the resulting ggplot object doesn't know about the original aesthetic mappings, scales, etc.

I asked for help with this on stackoverflow (https://stackoverflow.com/q/79804257/3962066) and was told that this is a very hard problem. So I guess I'm asking here, is there some way for ggplot2 to make this easier? I.e. can ggplot2 provide a mechanism to allow user modification of the gtable -- adding new rows/columns and grobs -- that fits in a normal ggplot2 pipeline?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions