ggplot2-秤在哪里建造?

eok*_*eok 5 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
)
Run Code Online (Sandbox Code Playgroud)

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
  }
)
Run Code Online (Sandbox Code Playgroud)

但是当我运行例如

ggplot(data.frame(x = rep(c("y", "n"), 6), y = rep(c("y", "n"), each = 6)), 
       aes(x = x, y = y)) + 
  geom_tile2()
Run Code Online (Sandbox Code Playgroud)

xy来自数字setup_data功能的stat及以后。浏览软件包的Github存储库,我似乎无法找到这种转换为坐标的实际位置?

Z.L*_*Lin 4

长话短说

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

长解释

ggplot2我通常会分两个阶段考虑使用包创建绘图所涉及的步骤:

  1. 地块建设。这是当一个新的 ggplot对象(通过初始化ggplot())和添加到它的所有geom_*// stat_*// facet_*/图层组合成一个 ggplot 对象时。如果我们写类似的东西,我们就停在这里。GH 代码在这里:plot-construction.rscale_*coord_*p <- ggplot(mpg, aes(class)) + geom_bar()
  2. 情节渲染。此时,组合的 ggplot 对象被转换为可渲染的对象(通过ggplot_build()),并进一步转换为 grobs 的 gtable(通过ggplot_gtable())。这通常是通过 ggplot 对象的 print/plot 方法触发的(请参见此处),但我们也可以使用ggplotGrob(),它直接返回转换后的 gtable 对象,减去打印步骤。ggplot_build/此处的 GH 代码ggplot_gtableplot-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
Run Code Online (Sandbox Code Playgroud)

我们开始单步执行该函数:

> 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")
}
Run Code Online (Sandbox Code Playgroud)

在调试模式下,我们可以在每个步骤之后进行检查,以检查与ggplot 对象str(data[[i]])层关联的数据(在本例中 = 1,因为只有 1 个 geom 层)。ii

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
Run Code Online (Sandbox Code Playgroud)

Stat*setup_datadata <- by_layer(function(l, d) l$compute_statistic(d, layout))(参见ggplot2:::Layer$compute_statistic 此处)触发的,这发生在这一步之后。这就是为什么当您在 中插入打印语句时StatIdentity2$setup_data,数据已经是数字形式了。

( 和Geom*setup_data由 触发的data <- by_layer(function(l, d) l$compute_geom_1(d)),甚至更晚发生。)

在确定map_position发生事情的步骤后,我们可以再次运行调试模式并进入该函数以准确查看发生了什么。在这一点上,恐怕我真的不知道你的用例是什么,所以我不得不让你自己解决。