学习了grob 和viewport,我们可不可以用它们,通过创建一个个绘图对象,像搭积木般来画个图呢?
来试试吧~
还有一些grid 提供的好用的函数。
先前我们通过viewport
创建画布,除此之外,还有一些方法。
grid.show.viewport(plotViewport())
plotViewport
我们还可以通过margin 参数自由调整,类似base 包中的par(mar)
:
比如:grid.show.viewport(plotViewport(margins = c(5,4,2,2)))
对应顺序c(bottom, left, top, right)
表示与下、左、上、右距离(inch)分别是5,4,2,2。
grid.show.viewport(gridBase::baseViewports()$plot)
grid.show.viewport(gridBase::baseViewports()$plot)
直接通过数据来适配画布:
除了[[91-R可视化23-底层绘图系统grid学习之grob对象]] 中介绍的,先通过xxGrob 方法获得grob 对象,我们还可以直接调用grid.xx 进行绘图,比如:
vp_background <- plotViewport(margins = c(5,4,2,2))
pushViewport(vp_background)
grid.rect()
首先我们创建两个画布,对应画图的背景以及用于画图的坐标中的画布:
vp_background <- plotViewport(c(5,4,2,2))
pushViewport(vp_background)
vp_plot <- dataViewport(iris$Petal.Length, iris$Petal.Width)
pushViewport(vp_plot)
接下来将散点图的各个部分画出来:
pushViewport(plotViewport(c(0.3,0.3,0.3,0.3),name = "vp_backgroud"
))
grid.rect(gp = gpar(lty = "dashed"))
pushViewport(plotViewport(c(5,4,2,2),name = "vp_backgroud2"))
pushViewport(dataViewport(iris$Petal.Length,
iris$Petal.Width,
name = "vp_plot"))
grid.rect()
grid.points(iris$Petal.Length, iris$Petal.Width,
name = "my_point")
grid.text("Petal.Length \n VS \n Petal.Width",
x = 0.3, y = 0.8)
grid.xaxis()
grid.yaxis()
grid.text("temperature", y = unit(-3, "line"))
grid.text("pressure", x = unit(-3, "line"), rot = 90)
需要注意的是,后画的内容会覆盖在先画的内容上面,因此我们的操作都是按照先大后小的原则,比如最外围的dashed rectangle,我们就最先画出来。
此外,关于grid.text("pressure", x = unit(-3, "line"), rot = 90)
的操作,目前我也并不理解,先挖个坑吧。
这时候,我们可不可以将这个绘图结果转换成ggplot 对象呢?比如结合grid 和ggplot 操作图形对象?
亦或是说,我们如何通过组合grob 在不同图纸下一步步作出ggplot 的整合体呢?
也留个坑吧,不知道能不能做到。
[1]
4.7 Building New Graphical Elements | Mastering Software Development in R (bookdown.org): https://bookdown.org/rdpeng/RProgDA/building-new-graphical-elements.html