`geom_abline()` 如何不影响 x 和 y 尺度?

How does `geom_abline()` not affect the x and y scales?

有谁知道 geom_abline() 中的哪个参数不影响 x 和 y 尺度?

函数 draw_panel() w/i GeomAbline 获取基础“范围”,但该线通常应位于原始比例之外:

GeomAbline <- ggproto("GeomAbline", Geom,
  draw_panel = function(data, panel_params, coord) {
    ranges <- coord$backtransform_range(panel_params)

    data$x    <- ranges$x[1]
    data$xend <- ranges$x[2]
    data$y    <- ranges$x[1] * data$slope + data$intercept
    data$yend <- ranges$x[2] * data$slope + data$intercept

    GeomSegment$draw_panel(unique(data), panel_params, coord)
  },

  default_aes = aes(colour = "black", size = 0.5, linetype = 1, alpha = NA),
  required_aes = c("slope", "intercept"),

  draw_key = draw_key_abline
)

我的猜测是 geom_abline()ggplot2:layer() 中的 arguments/functions ggplot2::StatIdentityggplot2::PositionIdentity 集。但我不明白这是如何工作的?我的动机是写一个新的 geom_*,它也不影响 x 和 y 尺度。

根据@teunbrand的评论,解决方案如下:

ggplot2::scale_x_continuous() 内部,只有以下美学可以影响 x 缩放:c("x", "xmin", "xmax", "xend", "xintercept", "xmin_final", "xmax_final", "xlower", "xmiddle", "xupper", "x0")。但是,由于 geom_abline() 不包含任何这些美学,因此比例不受影响。

这同样适用于 y 缩放。顺便说一句,变量对应于ggplot2:::ggplot_global$x_aesggplot2:::ggplot_global$y_aes中的字符,但由于我不知道的原因,这些变量没有被使用。

为了便于说明,我重写了 geom_point(),但为了美观 c("x_new", "y")

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


GeomMyPoint <- ggplot2::ggproto("GeomMyPoint", ggplot2::GeomPoint,
  required_aes = c("x_new", "y"),
  
  draw_panel = function(data, panel_scales, coord) {
    if (is.character(data$shape)) {
      data$shape <- translate_shape_string(data$shape)
    }

    ## Transform the data first
    coords <- coord$transform(data, panel_scales)

    ## Construct a grid grob
    grid::pointsGrob(
      x = coords$x_new,
      y = coords$y,
      pch = coords$shape,
      gp = grid::gpar(
        col = alpha(coords$colour, coords$alpha),
        fill = alpha(coords$fill, coords$alpha),
        fontsize = coords$size * ggplot2::.pt + coords$stroke * ggplot2::.stroke / 2,
        lwd = coords$stroke * ggplot2::.stroke / 2
      )
    )
  }
)

没有x美学的geom_my_point()的输出对应于图形“gg2”;因此红点不影响 x 尺度:

d <- data.frame(x = runif(200))
d$y <- 1 * d$x + rnorm(200, 0, 0.2)
d$x2 <- d$x * 2

require("ggplot2")
gg1 <- ggplot(d) + geom_point(aes(x, y)) + geom_point(aes(x = x2, y = y), col = 2) + ggtitle("gg1")
gg2 <- ggplot(d) + geom_point(aes(x, y)) + geom_my_point(aes(x_new = x2, y = y), col = 2) + ggtitle("gg2")