ggplot2 - 正在建造的秤?

时间:2018-04-08 13:35:25

标签: r ggplot2 ggproto

我想看看例如因子值变为数字值。我尝试过,例如在任何地方添加print语句......

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

GeomTile2 <- ggproto("GeomTile2", GeomRect,
  extra_params = c("na.rm", "width", "height"),

  setup_data = function(data, params) {
    print(data)

    data$width <- data$width %||% params$width %||% resolution(data$x, FALSE)
    data$height <- data$height %||% params$height %||% resolution(data$y, FALSE)

    transform(data,
              xmin = x - width / 2,  xmax = x + width / 2,  width = NULL,
              ymin = y - height / 2, ymax = y + height / 2, height = NULL
    )
  },

  default_aes = aes(fill = "grey20", colour = NA, size = 0.1, linetype = 1,
                    alpha = NA),

  required_aes = c("x", "y"),

  draw_key = draw_key_polygon
)

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

StatIdentity2 <- ggproto("StatIdentity2", Stat,

  setup_data = function(data, params) {
    print(data)
    data
  },
  compute_layer = function(data, scales, params) {
    print(data)
    print("stat end")
    data
  }
)

但是当我跑步时。

ggplot(data.frame(x = rep(c("y", "n"), 6), y = rep(c("y", "n"), each = 6)), aes(x = x, y = y)) + geom_tile2()

xy是来自setup_data及以后的stat函数的数字...并且通过Github查看我似乎无法找到这种转换到坐标实际上发生了什么?

1 个答案:

答案 0 :(得分:1)

TL; DR

通过ggplot2:::Layout$map_position()函数完成x / y从因子到数值比例的转换,当前代码在这里:layout.r

详细说明

我通常会想到在两个阶段中使用ggplot2包创建绘图的步骤:

  1. 绘制 构造 。这是将新的ggplot对象(通过ggplot()初始化)和所有geom_* / stat_* / facet_* / scale_* / coord_*层添加到它被组合成一个ggplot对象。如果我们写类似p <- ggplot(mpg, aes(class)) + geom_bar()的东西,我们就在这里停止。此处的GH代码:plot-construction.r
  2. 绘制 渲染 。这是将组合的ggplot对象转换为可以渲染的对象(通过ggplot_build())并进一步转换为grob的gtable(通过ggplot_gtable())的时候。这通常是通过ggplot对象的print / plot方法触发的(请参见here),但是我们也可以使用ggplotGrob(),它直接返回转换后的gtable对象,减去打印步骤。 ggplot_build / ggplot_gtable的GH代码在这里:plot-build.r

根据我的经验,我们可能想调整的大多数步骤都是在情节渲染阶段内进行的,在ggplot2:::ggplot_build.ggplot / ggplot2:::ggplot_gtable.ggplot_built上运行调试是弄清楚事情在哪里的很好的第一步。发生。

在这种情况下,运行后

debugonce(ggplot2:::ggplot_build.ggplot)

ggplot(data.frame(x = rep(c("y", "n"), 6), 
                  y = rep(c("y", "n"), each = 6)), 
       aes(x = x, y = y)) + 
  geom_tile() # no need to use the self-defined geom_tile2 here

我们开始逐步执​​行该功能:

> ggplot2:::ggplot_build.ggplot
function (plot) 
{
    plot <- plot_clone(plot)
    if (length(plot$layers) == 0) {
        plot <- plot + geom_blank()
    }
    layers <- plot$layers
    layer_data <- lapply(layers, function(y) y$layer_data(plot$data))
    scales <- plot$scales
    by_layer <- function(f) {
        out <- vector("list", length(data))
        for (i in seq_along(data)) {
            out[[i]] <- f(l = layers[[i]], d = data[[i]])
        }
        out
    }
    data <- layer_data
    data <- by_layer(function(l, d) l$setup_layer(d, plot))
    layout <- create_layout(plot$facet, plot$coordinates)
    data <- layout$setup(data, plot$data, plot$plot_env)
    data <- by_layer(function(l, d) l$compute_aesthetics(d, plot))
    data <- lapply(data, scales_transform_df, scales = scales)
    scale_x <- function() scales$get_scales("x")
    scale_y <- function() scales$get_scales("y")
    layout$train_position(data, scale_x(), scale_y())
    data <- layout$map_position(data)
    data <- by_layer(function(l, d) l$compute_statistic(d, layout))
    data <- by_layer(function(l, d) l$map_statistic(d, plot))
    scales_add_missing(plot, c("x", "y"), plot$plot_env)
    data <- by_layer(function(l, d) l$compute_geom_1(d))
    data <- by_layer(function(l, d) l$compute_position(d, layout))
    layout$reset_scales()
    layout$train_position(data, scale_x(), scale_y())
    layout$setup_panel_params()
    data <- layout$map_position(data)
    npscales <- scales$non_position_scales()
    if (npscales$n() > 0) {
        lapply(data, scales_train_df, scales = npscales)
        data <- lapply(data, scales_map_df, scales = npscales)
    }
    data <- by_layer(function(l, d) l$compute_geom_2(d))
    data <- by_layer(function(l, d) l$finish_statistics(d))
    data <- layout$finish_data(data)
    structure(list(data = data, layout = layout, plot = plot), 
        class = "ggplot_built")
}

在调试模式下,我们可以在每一步之后检查str(data[[i]]),以检查与ggplot对象的图层i相关的数据(在这种情况下,i = 1,因为只有1个geom层。

Browse[2]> 
debug: data <- lapply(data, scales_transform_df, scales = scales)
Browse[2]> 
debug: scale_x <- function() scales$get_scales("x")
Browse[2]> str(data[[1]]) # still factor after scale_transform_df step
'data.frame':   12 obs. of  4 variables:
 $ x    : Factor w/ 2 levels "n","y": 2 1 2 1 2 1 2 1 2 1 ...
 $ y    : Factor w/ 2 levels "n","y": 2 2 2 2 2 2 1 1 1 1 ...
 $ PANEL: Factor w/ 1 level "1": 1 1 1 1 1 1 1 1 1 1 ...
 $ group: int  4 2 4 2 4 2 3 1 3 1 ...
  ..- attr(*, "n")= int 4

# ... omitted

debug: data <- layout$map_position(data)
Browse[2]> 
debug: data <- by_layer(function(l, d) l$compute_statistic(d, layout))
Browse[2]> str(data[[1]]) # numerical after map_position step
'data.frame':   12 obs. of  4 variables:
 $ x    : int  2 1 2 1 2 1 2 1 2 1 ...
 $ y    : int  2 2 2 2 2 2 1 1 1 1 ...
 $ PANEL: Factor w/ 1 level "1": 1 1 1 1 1 1 1 1 1 1 ...
 $ group: int  4 2 4 2 4 2 3 1 3 1 ...
  ..- attr(*, "n")= int 4

Stat*的{​​{1}}由setup_data触发(请参阅data <- by_layer(function(l, d) l$compute_statistic(d, layout)) here),这发生在 之后 。这就是为什么在ggplot2:::Layer$compute_statistic中插入打印语句时,数据已经是数字形式的原因。

(并且StatIdentity2$setup_data的{​​{1}}由Geom*触发,甚至更晚发生。)

在将setup_data确定为发生事情的步骤之后,我们可以再次运行调试模式并进入此函数以查看发生了什么。在这一点上,恐怕我真的不知道您的用例是什么,所以我将不得不留给您。