追求系列化、高质量的R语言教程
本篇来介绍如何定义一个几何图形函数,即geom_*()
类函数。
其实,ggplot2
工具包中本身就有绘制阶梯图的几何图形函数geom_step()
。不过,本篇目的在于介绍自定义函数的方法,因此仍使用这个案例,所定义的函数可视为geom_step()
函数的简化版。
定义几何图形函数的步骤如下:
定义一个新的ggproto对象
Geom*
;该过程中会调用grid
工具包中的函数;定义新函数;该过程中会使用语句
layer(geom = Geom*, ...)
。
本篇目录如下:
1 定义GeomStepLine对象
2 定义geom_stepline函数
3 用到的属性/方法说明
3.1 default_aes属性
3.2 draw_key属性
3.3 draw_panel方法
1 定义GeomStepLine对象
如下是定义GeomStepLine对象的代码,其中重要部分已经标红:
library(ggplot2)
GeomStepLine <- ggproto("GeomStepLine", Geom,
required_aes = c("x", "y"),
default_aes = aes(size = 1.5, col = "black"),
draw_key = draw_key_path,
draw_panel = function(data, panel_params, coord, type) {
coords <- coord$transform(data, panel_params)
coords = coords[order(coords$x), ]
coords = data.frame(apply(coords, 2, rep, each =2))
n = dim(coords)[1]
if (type == 1) {coords$x = c(coords$x[2:n], NA)}
if (type == 2) {coords$y = c(coords$y[2:n], NA)}
coords = data.frame(coords[complete.cases(coords),])
grid::linesGrob(
x = coords$x,
y = coords$y,
gp = grid::gpar(lwd = coords$size,
col = coords$colour)
)
}
)
上述代码是通过更改Geom
对象如下4个属性或方法创建的GeomStepLine
对象:
required_aes:函数所必需的美学参数;
default_aes:设置非必需美学参数的默认值;
draw_key:图例形状;
draw_panel:创建grob对象。
其中required_aes
属性已经在前面两篇推文中使用过了,本篇第3节会分别介绍另外三个属性或方法。