0

I am working on custom ggplot2 items and want to compute the size of the actual plot without the margins.

Suppose this plot

ggplot(mtcars, aes(x = cyl, y = hp )) + geom_point() + ggtitle('test') + theme_bw()

I need to retrive the length (relative or absolute) of the margins (see red lines) or somehow the size of the plot and its relative position to the top left corner.

enter image description here

Is there any way to retrieve this info from the ggplot2 object?

Arkadi w
  • 129
  • 22
  • *very* related https://stackoverflow.com/questions/60803424/npc-coordinates-of-geom-point-in-ggplot2 – tjebo May 05 '20 at 07:18
  • This is still relying on internal margins only – Arkadi w May 05 '20 at 19:41
  • [and also very related.](https://stackoverflow.com/a/16442029/7941188) Note Baptiste's comment *the plot panel size will be 0 by default, as it is meant to be calculated on-the-fly according to the device (viewport) it lives in, not the opposite.* – tjebo May 05 '20 at 21:26
  • *This is still relying on internal margins only* - What do you mean? The linked post does pretty much show what you are asking for? If not, please kindly clarify how your question is different. Cheers – tjebo May 05 '20 at 21:29
  • I need the size of the inner plot. As in, image the plot is 400x300, I need to know what are the margins and what is the size of the inner plot (inside the box, suppose 380x250) – Arkadi w May 07 '20 at 16:45

1 Answers1

1

Does this help?

library(ggplot2)

p1 <- 
  ggplot(mtcars, aes(x = cyl, y = hp )) + geom_point() + ggtitle('test') + theme_bw()

#retrieve plot margin information
p1$theme$plot.margin

#Gives you:    

    p1$theme$plot.margin
    ## [1] 5.5pt 5.5pt 5.5pt 5.5pt



p2 <- 
  p1 +
  theme(plot.margin = margin(1, 2, 3, 4, "cm"))

p2$theme$plot.margin

# gives you:

    p2$theme$plot.margin
    ## [1] 1cm 2cm 3cm 4cm


Peter
  • 11,500
  • 5
  • 21
  • 31
  • Not really, this computed the margins without the axis labels. If you replace by theme(plot.margin = margin(1, 2, 3, 0, "cm")) you will still see space between outer area and inner plot – Arkadi w May 05 '20 at 08:19