ggplot2 | 開發(fā)自己的畫圖函數(shù)

??如何基于ggplot2快速開發(fā)自己的畫圖函數(shù)?分為兩步走:第一步,構(gòu)建一個(gè)圖形對(duì)象;第二步,定義一個(gè)圖層函數(shù)。下面用一個(gè)棒棒糖圖的示例來說明。

??首先,用ggproto構(gòu)建相應(yīng)的圖形類,該類里面包含繪圖需要的屬性和函數(shù)等信息。如下面的代碼,定義了一個(gè)GeomLollipop類,里面包含了棒棒糖的默認(rèn)圖形屬性,如形狀、線條粗細(xì)、顏色等,以及繪圖的底層函數(shù)。

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))
})

??然后,基于自定義的圖形類,定義一個(gè)新的圖層函數(shù)。如下面的代碼,定義了一個(gè)繪圖函數(shù)geom_lollipop,該函數(shù)會(huì)使用到前面定義的圖形類GeomLollipop,從里面獲取繪圖時(shí)需要的圖形參數(shù)信息。

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, ...))
}

??最后,調(diào)用自定義的繪圖函數(shù)來畫圖。下面使用數(shù)據(jù)來測(cè)試一下上面定義的棒棒糖圖函數(shù),看看效果怎么樣:

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

結(jié)果如下:

??ggplot2居然提前預(yù)留了開發(fā)新的繪圖函數(shù)的接口,可以讓工作者快速定義自己的繪圖函數(shù),擴(kuò)展可視化的功能,一句話形容:太贊了!怎么樣,有沒有自定義繪圖函數(shù)的沖動(dòng),心動(dòng)不如行動(dòng)~


往期回顧

R包安裝的4種姿勢(shì)
clusterProfiler: No gene can be mapped | 怎么破?
R語言的碎碎念
linux入門學(xué)習(xí)指南
武林大會(huì)之對(duì)角線熱圖

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容