美文网首页ggplot2绘图
ggplot2 | 开发自己的画图函数

ggplot2 | 开发自己的画图函数

作者: 生信云笔记 | 来源:发表于2023-08-19 17:11 被阅读0次

  如何基于ggplot2快速开发自己的画图函数?分为两步走:第一步,构建一个图形对象;第二步,定义一个图层函数。下面用一个棒棒糖图的示例来说明。

  首先,用ggproto构建相应的图形类,该类里面包含绘图需要的属性和函数等信息。如下面的代码,定义了一个GeomLollipop类,里面包含了棒棒糖的默认图形属性,如形状、线条粗细、颜色等,以及绘图的底层函数。

library(ggplot2)

GeomLollipop <- ggproto("GeomLollipop", Geom, required_aes = c("x","y"), default_aes = aes(shape = 19, lwd = 2, colour='blue'),
      draw_key = draw_key_point, 
      draw_panel = function(data, panel_params, coord) {
           ## Transform the data first
           coords <- coord$transform(data, panel_params)
           ## Construct a ponit grob
           p1 <- pointsGrob(
                    x = coords$x,
                    y = coords$y,
                    pch = coords$shape,
                    gp = gpar(col = coords$colour, lwd = coords$size))
            ## Construct a segment grob
            p2 <- segmentsGrob(x0 = coords$x,
                    x1 = coords$x,
                    y0 = 0,
                    y1 = coords$y,
                    gp = gpar(lwd = coords$size, col = coords$colour))

           gTree(children = gList(p1, p2))
})

  然后,基于自定义的图形类,定义一个新的图层函数。如下面的代码,定义了一个绘图函数geom_lollipop,该函数会使用到前面定义的图形类GeomLollipop,从里面获取绘图时需要的图形参数信息。

geom_lollipop <-  function(mapping = NULL, data = NULL, stat = "identity", position = "identity", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, ...) {
        layer(geom = GeomLollipop , mapping = mapping,  
              data = data, stat = stat, position = position, 
              show.legend = show.legend, inherit.aes = inherit.aes,
              params = list(na.rm = na.rm, ...))
}

  最后,调用自定义的绘图函数来画图。下面使用数据来测试一下上面定义的棒棒糖图函数,看看效果怎么样:

df <- data.frame(x=1:10,y=1:10)
p <- ggplot(df,aes(x,y))+geom_lollipop()
p <- p + theme_test()
p

结果如下:

  ggplot2居然提前预留了开发新的绘图函数的接口,可以让工作者快速定义自己的绘图函数,扩展可视化的功能,一句话形容:太赞了!怎么样,有没有自定义绘图函数的冲动,心动不如行动~

往期回顾

R包安装的4种姿势
clusterProfiler: No gene can be mapped | 怎么破?
R语言的碎碎念
linux入门学习指南
武林大会之对角线热图

相关文章

网友评论

    本文标题:ggplot2 | 开发自己的画图函数

    本文链接:https://www.haomeiwen.com/subject/wpdjmdtx.html