简体   繁体   中英

How to retrieve ggplot2 inner plot size and margins length

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.

在此处输入图像描述

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

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


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM