r - Save plot with a given aspect ratio -
i'm working awesome library ggplot2. figured out how set aspect ratio of plot using coord_fixed
. now, i'd save plot pdf specified width (e.g 10 cm) , let required height calculated. did not figure out how achieve this. possible?
you can use grid functions calculate full size of ggplot grob, there (edit: @ least) 2 caveats:
an device window open, unit conversion
the plot panel size 0 default, meant calculated on-the-fly according device (viewport) lives in, not opposite.
that being said, following function attempts open device fits ggplot exactly,
library(ggplot2) library(grid) sizeit <- function(p, panel.size = 2, default.ar=1){ gb <- ggplot_build(p) # first check if theme sets aspect ratio ar <- gb$plot$coordinates$ratio # second possibility: aspect ratio set coordinates, results in # use of 'null' units gtable layout. let's find out g <- ggplot_gtable(gb) nullw <- sapply(g$widths, attr, "unit") nullh <- sapply(g$heights, attr, "unit") # ugly hack extract aspect ratio these weird units if(any(nullw == "null")) ar <- unlist(g$widths[nullw == "null"]) / unlist(g$heights[nullh == "null"]) if(is.null(ar)) # if aspect ratio wasn't specified plot ar <- default.ar # ensure panel.size larger dimension if(ar <= 1 ) panel.size <- panel.size / ar g$fullwidth <- convertwidth(sum(g$widths), "in", valueonly=true) + panel.size g$fullheight <- convertheight(sum(g$heights), "in", valueonly=true) + panel.size / ar class(g) <- c("sizedgrob", class(g)) g } print.sizedgrob <- function(x){ # note: dev.new doesn't seem respect parameters # when called rstudio; in case # may replaced x11 or quartz or ... dev.new(width=x$fullwidth, height=x$fullheight) grid.draw(x) } p1 <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point() + coord_fixed() + theme(plot.background = element_rect(colour = "red")) p2 <- p1 + aes(x = mpg, y = wt) # need explicit dummy device open, otherwise it's bit off # no apparent reason can understand dev.new() sizeit(p1, 0.1)
sizeit(p2, 2)
Comments
Post a Comment