您也可以为此使用 geom_path()
X <- 1:5
Y <- c(2, 6, 4, 7, 12)
DF <- data.frame(X, Y)
ggplot(data = DF, aes(x = X, y = Y)) +
geom_point() +
geom_line() +
geom_path(data = data.frame(x = c(-Inf, 4.5, 4.5), y = c(approx(X, Y, 4.5)$y, approx(X, Y, 4.5)$y, -Inf)), aes(x, y), color = "red", linetype = 2)
如果您希望它更灵活地进行更多拦截,您可以使用此功能。请注意该...
部分,以便您可以传递geom_path
参数,例如颜色、线型、大小等。它支持基于x
值或基于值的截距y
。
my_intercept <- function(x, y, ...) {
if (!missing(x)) dt <- data.frame(x = c(-Inf, x, x), y = c(approx(X, Y, x)$y, approx(X, Y, x)$y, -Inf))
if (!missing(y)) dt <- data.frame(x = c(-Inf, approx(Y, X, y)$y, approx(Y, X, y)$y), y = c(y, y, -Inf))
geom_path(data = dt, aes(x, y), ...)
}
ggplot(data = DF, aes(x = X, y = Y)) +
geom_point() +
geom_line() +
my_intercept(x = 4.5, color = "blue", linetype = 2) +
my_intercept(y = 5, color = "red", linetype = 4)