Resources for understanding how ggplot2 layers visual elements?

Working on ggflags, I've been learning a lot about how ggplot2 builds up gTrees in Grid to compose a plot. I've been thinking about an idea for a package that would basically ingest a ggplot object and spit out a bunch of numbered SVGs with the different elements of the plot—using the same plotting space but with transparent backgrounds, so that the SVGs could be overlaid to 'build a plot up' when presenting. It could potentially also integrate with other packages like officer, so that you could knock out a Powerpoint slide that has the layers positioned and animated per-click right off the bat.

Can anyone point me to either:

  1. A package that already does this (so I don't go reinventing the wheel), or
  2. Resources on how ggplot arranges its hierarchy in Grid, so I can start thinking about how to identify the elements to isolate?

Thanks! :smiley:

2 Likes

I would love to see this, too, particularly with respect to the positioning calculation of the elements..

These might be way too simple for what you're doing, but @thomasp85's "Beneath the Canvas" post


and also the unggplot() function from ggpipe

came to mind.

There's also a post from @sthda_en that might be relevant!

I understand umm…embarrassingly :flushed: little of the ggplot2 internals, but thought I'd put 'em out there nonetheless!

3 Likes

Thanks @mara! My gut feeling is that it's better to try and manipulate the gTree after everything's rendered, rather than try to mess with the plotting object before it's rendered—otherwise, I'd have to make a solution that works for every possible ggplot object. It seems more relevant to try to identify (in an automated way) which gTree nodes are relevant groups of visual features. One way to do that could to some analysis of the whole tree, but maybe if I understand ggplot2 better, I can find a way to track the geoms and groups and such to their eventual gTree names (which look pretty nondescript to me).

As a side note, the transparency stuff is also interesting because I've done a few overlaid density plots recently and felt that they'd look a lot better with a different alpha blending mode. Not sure whether ggplot2 supports that, though!

EDIT: re. the blending mode stuff, I'd love to get @hadley and @baptiste's opinions on whether anything has changed since this thread in 2010. I assume not, but you never know :slight_smile:

1 Like

gridSVG might be worth a look; it's meant to reflect the grid hierarchy more closely than the other svg devices,

https://sjp.co.nz/projects/gridsvg/demos/gapminder-multi/

1 Like

@baptiste Yeah, I noticed that gridSVG::grid.export gave a more structured output than ggsave (which is also great for building interactivity into an exported plot later). Thanks!