Access aesthetic mappings of previous ggplot2 layer

Does anyone know how to dynamically access the aesthetics of a previous layer in ggplot2?

For example, say that I have created a custom geom, which implements a statistical transformation on some input data. But the way this transformation works should (ideally) adjust according to any aesthetics described in previous layers. In particular, it should adjust depending on which variable is specified on the x axis and which variable is specified on the y axis.

Background: I've written a simple package for plotting 2D decision tree partitions in ggplot2: parttree. To see the full effect, you'd want to plot these partitions together with the raw data. And this generally works well, for example:

# remotes::install_github("grantmcdermott/parttree")

iris_tree = rpart(Species ~ Petal.Length + Petal.Width, data=iris)

ggplot(data = iris, aes(x=Petal.Length, y=Petal.Width)) +
  geom_point(aes(col=Species)) +  
  geom_parttree(data = iris_tree, aes(fill=Species), alpha = 0.1) +

However, one annoyance is that the axes orientation of the partitions can sometimes be switched around relative to the raw data, depending on how the user chooses to specify her original plot aesthetic. For example:

ggplot(data = iris, aes(x=Petal.Width, y=Petal.Length)) + ## x and y aesthetics switched!
  geom_point(aes(col=Species)) +  
  geom_parttree(data = iris_tree, aes(fill=Species), alpha = 0.1) +

(Longer discussion here.)

My thinking is that if I can access the aesthetics of, say, the geom_point() layer — which variable is on the x-axis and which variable is on the y-axis — then I can dynamically pass this information on to my bespoke geom_parttree() layer. That way I can adjust the underlying data transformation and always ensure the correct orientation of the tree partition splits relative to the raw data in the final plot call.

Ofc I'm very much open to other solutions too.

Thanks in advance.

PS — My question here is related to this one. But AFAICT none of the proposed workarounds are applicable to my situation. In particular, I don't want to access the inherited data object; I want to access potentially inherited aesthetics and then map those on to a totally new data transformation.

EDIT: Added reprex to save people having to click through to the packge repo.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.