思路
grid的画图函数都含有just,但是just参数的是怎么调节图形位置的总是让人非常费解,于是便写了代码来一探究竟。
思路非常简单:放一个2*2的布局viewport,每个布局里面放一个viewport,每个viewport都用了不同的just参数。just之后的矩形用蓝色显示,中心点的移动用箭头表示出来, 这样每个参数对应图形怎么移动的都能一目了然。从以下的代码也能学到如何安排布局, 如何使用grobX和grobY获得grob对象的坐标, 如何进行基本的viewport切换等。
代码
library(grid)
grid.newpage() # new page
pushViewport(viewport(layout = grid.layout(2,2))) # 2 *2 layout
# just top
pushViewport(viewport(layout.pos.col = 1, layout.pos.row = 1))
grid.rect()
r1 <- rectGrob(0.5, 0.5, width = 0.2, height = 0.2, name = "r1")
r2 <- rectGrob(0.5, 0.5, width = 0.2, height = 0.2, just = c("top"),gp=gpar(col="blue"), name = "r2")
grid.draw(r1)
grid.draw(r2)
grid.segments(0.5,0.5,grobX(r2, 90), grobY(r2, 0), arrow=arrow(angle=15, type="closed"), gp=gpar(fill="black"))
grid.text("just: top" ,0.6, 0.8)
upViewport()
# just left and top
pushViewport(viewport(layout.pos.col = 1, layout.pos.row = 2))
grid.rect()
r1 <- rectGrob(0.5, 0.5, width = 0.2, height = 0.2, name="r1")
r2 <- rectGrob(0.5, 0.5, width = 0.2, height = 0.2, just = c("left", "top"), gp=gpar(col="blue"), name="r2")
grid.draw(r1)
grid.draw(r2)
grid.segments(0.5, 0.5, grobX(r2, 90), grobY(r2, 0), arrow=arrow(angle=15, type="closed",), gp=gpar(fill="black"))
grid.text("just: left and top", 0.6, 0.8)
upViewport()
# just left and bottom
pushViewport(viewport(layout.pos.col = 2, layout.pos.row = 1))
grid.rect()
r1 <- rectGrob(0.5, 0.5, width = 0.2, height = 0.2, name="r1")
r2 <- rectGrob(0.5, 0.5, width = 0.2, height = 0.2, just = c("left", "bottom"), gp=gpar(col="blue"), name="r2")
grid.draw(r1)
grid.draw(r2)
grid.segments(0.5, 0.5,grobX(r2, 90), grobY(r2, 0), arrow=arrow(angle=15, type="closed",), gp=gpar(fill="black"))
grid.text("just: left and bottom", 0.6, 0.8)
upViewport()
# just right bottom
pushViewport(viewport(layout.pos.col = 2, layout.pos.row = 2))
grid.rect()
r1 <- rectGrob(0.5, 0.5, width = 0.2, height = 0.2, name="r1")
r2 <- rectGrob(0.5, 0.5, width = 0.2, height = 0.2, just = c("right", "bottom"), gp=gpar(col="blue"), name = "r2")
grid.draw(r1)
grid.draw(r2)
grid.segments(0.5,0.5,grobX(r2, 90), grobY(r2, 0), arrow=arrow(angle=15, type="closed",), gp=gpar(fill="black"))
grid.text("just: right and bottom", 0.6, 0.8)
upViewport()
结果
结论
- just参数对图形进行相反的调节,比如想向上调节图形,就得调节just="bottom",也可以理解为真实位置相对于画图位置,比如真实位置要比画图位置要低,就用just="bottom“
- grobX角度为90时, grobY 角度为0时,可获得图形的中心位置, grobX 为0时X位置在图形的最右, grobY 为0时Y位置在图形的中间