首页 文章

编写ggplot自定义几何函数

提问于
浏览
3

我正在编写一个函数来创建ggplot的散点图,其中点的大小表示具有相同X和Y坐标的点的数量 .

我有一个有效的功能:

require(dplyr)
plot_size_bubbles <- function(x,y) {
  dd = data.frame(x,y) %>%
    group_by(x,y) %>%
    summarise(n=n()) %>%
    ungroup()
  ggplot(dd, aes(x,y)) + geom_point(aes(size=n))
}

X = sample(1:3,10,replace = T)
Y = sample(1:3,10,replace = T)
plot_size_bubbles(X,Y)

我想以ggplot的风格作为从geom_point继承的自定义几何函数 . 也许我可以使用一些统计功能,不确定 . 基本上我想传递给ggplot一个数据框,映射x和y,并创建这个图而不事先计算点大小 . 喜欢

ggplot(data.frame(X,Y), aes(X,Y)) + geom_sizebubble()

此外,从原始数据框中获得x和y轴标签会很棒 .

希望有可能,我只是遗漏了一些东西 .

1 回答

  • 5
    stat_accum <- function(mapping = NULL, data = NULL,
                             geom = "point", position = "stack",
                             ...,
                             show.legend = NA,
                             inherit.aes = TRUE) {
    
      layer(
        data = data,
        mapping = mapping,
        stat = StatAccum,
        geom = geom,
        position = position,
        show.legend = show.legend,
        inherit.aes = inherit.aes,
        params = list(
          na.rm = na.rm,
          ...
        )
      )
    }
    
    StatAccum <- ggproto("StatAccum", Stat,
      compute_layer = function(data, scales, params) {
        odat <- dplyr::distinct(data, x, y, .keep_all=TRUE)
        data <- dplyr::count(data, x, y)
        data <- dplyr::left_join(data, odat, by=c("x", "y"))
        data$size <- data$n
        data$n <- NULL
        data
     }
    )
    
    set.seed(12)
    dplyr::data_frame(
      X = sample(1:5, 100, replace = TRUE),
      Y = sample(1:5, 100, replace = TRUE)
    ) -> xdf
    
    ggplot(xdf, aes(X, Y)) + geom_point()
    

    enter image description here

    ggplot(xdf, aes(X, Y)) + geom_point(stat="accum")
    

    enter image description here

相关问题