Getting "npc" coordinates of ggplot2 grob
Asked Answered
C

0

1

The grid package used for generating graphics in the R language uses so-called "normal parent coordinates" (npc) to position graphical objects ("grobs"). Is it possible to get the npc coordinates of a ggplot2 grob? This would be of major help for drawing lines (for connecting data points) across facets (ggplot, drawing line between points across facets contains a solution, but this is very hard to follow for beginners)

library(ggplot2)
library(grid)

# Generate some sample data
df <- data.frame(y=c(1,2,3),x=1,Set=LETTERS[1:3])

# Plot
ggplot(df,aes(x,y)) + 
  geom_point(aes(fill=Set),color="black",shape=21,size=3) + 
  facet_grid(~Set)

# It is easy to list the grobs, but I can't see their npc coordinates
grid.ls(grid.force())
Carisacarissa answered 9/2, 2018 at 16:47 Comment(8)
See if this addresses your needs: #38775827Williswillison
Thanks for your reply. ggplot makes it easy to add annotations within the coordinate system of a facet as described in the link. It is much more difficult to draw for example an arrow between two facets. This is the scenario which I would be interested.Carisacarissa
So what is it that you want to see? I suspect that you will need to push and pop a new viewPort that surrounds whichever of the existing grobs if you want to exceed their existing boundaries. (Just a guess ... I'm not a grid expert.)Williswillison
I don't think so. I think with turning off clipping, this should be no problem.Carisacarissa
OK. That might be another way of doing it if you had open viewPorts. But I suspect a grob doesn't "remember" where it got placed. I think I can construct an answer for your example if you unambiguously describe what is needed, but I am quite sure I cannot "see" inside the ggplot code. I'm even less of a ggplot expert than I am a (non)-grid-expert.Williswillison
Here's another nomination for an answer to what appears to be a duplicate question: #31690507Williswillison
@Carisacarissa Are you still looking for an answer, or an explanation of the linked solution?Marcelo
Thanks a lot. I realized that working with the grid graphics objects can sometimes be quite difficult. Especially starting from a ggplot, which can include many of them. I think, I will rather try to use R base graphics, although ggplot can generate really nice plots.Carisacarissa

© 2022 - 2024 — McMap. All rights reserved.