How do I manually fit a viewport with a fixed aspect ratio into its parent such that no space is wasted like ggplot can do?

ぐ巨炮叔叔 提交于 2019-12-04 09:18:33

ggplot2 uses grid layouts with null units and the respect argument to enforce aspect ratios. Here's an example,

library(grid)

ar <- (1+sqrt(5))/2
gl <- grid.layout(1,1,widths=unit(1,"null"), height=unit(1/ar,"null"), respect = TRUE)
grid.newpage()
grid.rect(vp=vpTree(viewport(layout = gl), 
                    vpList(viewport(layout.pos.row = 1, layout.pos.col = 1))))

user9169915 did it! Awesome! I am posting here his solution in procedural grid style, for reference. Additionally, I added the equidistant coordinate system.

ar <- (1+sqrt(5))/2 # aspect ratio
# Native coordinate system of the target viewport: make x and y equidistant
xrange <- c(0,5)
yrange <- xrange/arN

forDifferentSizes( paste0('L',letters[1:4]), seq(100, 500, length.out = 4), 250
  , fun = function(...){

  gl <- grid.layout(1,1,widths=unit(1,"null"), height=unit(1/ar,"null"), respect = TRUE)
  grid.newpage()
  pushViewport(viewport(layout = gl))
  annot('vp1') # see question for definition
  pushViewport(viewport(layout.pos.row = 1, layout.pos.col = 1,
                        xscale = xrange, yscale = yrange))
  annot('vp2')
  grid.grill(h=0:floor(yrange[2]), v=0:floor(xrange[2]), default.units = 'native')
  popViewport(2)

})

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!