Reputation: 515
I generated a random example plot with ggplot2 and multiple facets. I am interested in the exact positions of the individual panels and want to export the relative start and end coordinates of those panels as well as the picture of the plot (basically for point identification via mouseover events in a javascript context).
To get the information i need for the relative coordinates i use the grid package. Suppose p
to be the variable which stores my plot (after p <- ggplot(...)
).
With
pb <- ggplot_build(p)
pta <- ggplot_gtable(pb)
heights <- pta$heights
and analogously for the widths I get that information. For example, in this case I get for heigths
[1] 1lines 0cm+0lines 1null
[4] 0.25lines 1null 0.25lines
[7] 1null 0.532222222222222cm 1grobheight+0.5lines
[10] 0.5lines
where the entries with unit null
represent the panels. To be able to compare these I have to convert them into the same unit. null
I cannot convert but the remaining ones. Using that the viewport is 1npc (npc is a unit too) in width and length I can solve an equation which allows me to create the following image (screenshot from the RStudio Plots window) with the lines drawn with grid.lines()
:
So everything seems to work. Now if I rescale the Plot window in RStudio the lines are drawn at the wrong places. The reason is that some units like grobheight
are dependent on the current viewport. Hence, if I want to save the image (say 600 x 600 pixel) i have to do
png(fn, width = 600, height = 600)
pushViewport(viewport(width=0.5, height=0.5, xscale=c(0, 600), yscale=c(0, 600)))
print(p)
... #draw the lines
dev.off()
But.
Despite that, no matter how I save the image, say ggsave()
or png()
(the latter either with print(p)
oder grid.draw(pta)
) the actual proportions differ from the computed ones which were correct in the R environment.
A certain amount of the plotmargins seems to get cut off, and additional scaling is done apparently.
A png export looks like this for example:
The difference seems to be small, but that doesn't help. So, is there a way to save the image exactly as it is described in the gtable object pta
? Is it a matter of dpi or pointsize?
Many thanks for your help,
Mika
Upvotes: 3
Views: 1563
Reputation: 1053
Everything I've encountered with this exact issue stems back to the height and width call in the png()
or pdf()
or anything output call. Play with the height and width in order to best determine what it will look like.
If you want to know what it will look like when you export use x11(height= width= )
, note the units here are "in" so you will want to mimic that in your output function.
Upvotes: 1