我用線連接點繪制了一個圖。在這個圖中,我想從 x 軸上的一點到與繪圖線的交點畫一條垂直線。在交點處,我想畫一條到 Y 軸的水平線。我已經搜索了幾個網站、論壇和教程,但我仍然無法做到。有什么幫助嗎?
library(ggplot2)
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_vline(xintercept = 4.5,
linetype = 2)
到目前為止的結果:

所需結果示例:

uj5u.com熱心網友回復:
已經由@Eric 發表評論,但也由@akrun 在
uj5u.com熱心網友回復:
正如@Eric 在他的評論中已經提到的那樣,這geom_segment是實作您想要的結果的方法。此外,您必須手動計算y段應該切割的值,geom_line這可以使用approx. 快速方法可能如下所示:
library(ggplot2)
X <- 1:5
Y <- c(2, 6, 4, 7, 12)
DF <- data.frame(X, Y)
# vertical line
vsegment <- function(x, X, Y) {
geom_segment(aes(x = x, xend = x, y = -Inf, yend = approx(X, Y, x)$y),
linetype = 2)
}
# horizontal line
hsegment <- function(x, X, Y) {
geom_segment(aes(x = -Inf, xend = x, y = approx(X, Y, x)$y, yend = approx(X, Y, x)$y),
linetype = 2)
}
ggplot(data = DF,
aes(x = X,
y = Y))
geom_point()
geom_line()
vsegment(4.5, X, Y)
hsegment(4.5, X, Y)

uj5u.com熱心網友回復:
您也可以為此使用 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)

轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/394497.html
標籤:r ggplot2 线 geom-hline geom-vline
上一篇:按組自定義ggplot圖例
下一篇:在R中的圖表中設定列寬
