根据@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_aes
和中的字符ggplot2:::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
)
)
}
)
geom_my_point()
with noesthetic的输出x
对应于图形“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")
