我正在尝试限制geom_abline的范围。在下面的图中,我希望红线在xvalue 5处停止,蓝线在值5处开始(在图片中,我手工标记了需要删除的部分)。
obs:我理解aes和slope不能一起使用,但仍然将其作为伪代码的形式放在代码中,以澄清我希望ggplot2让我做什么。
library(tidyverse)
d <- data.frame(x=1:10,y=2:11)
d %>% ggplot(aes(x,y)) + geom_point() +
geom_abline(aes(xmax=5),slope = 1,color='red') +
geom_abline(aes(xmin=5),slope = 1,intercept = 3,color='blue')

R输出警告:
Warning messages:
1: geom_abline(): Ignoring `mapping` because `slope` and/or `intercept` were provided.
2: geom_abline(): Ignoring `mapping` because `slope` and/or `intercept` were provided.发布于 2021-08-08 13:39:21
您可以使用geom_function()来代替geom_abline(),并指定一个矢量化的函数。如果你不确定“向量化”一个函数是什么意思,我们的想法是,如果x的值在我们不想出现行的范围内,我们希望函数返回NA,否则返回该行。为了让你的函数像这样沿着每个x值求值,你需要让函数逐个求值(矢量化)。如果不向量化函数,就不能在其中使用if语句。
d %>% ggplot(aes(x,y)) + geom_point() +
# geom_abline(aes(xmax=5),slope = 1,color='red') +
geom_function(fun=Vectorize(function(x) {
if(x > 5)
return(NA)
else
return(x)
}), color='red') +
# geom_abline(aes(xmin=5),slope = 1,intercept = 3,color='blue') +
geom_function(fun=Vectorize(function(x) {
if(x > 5)
return(x+3)
else
return(NA)
}), color='blue')

https://stackoverflow.com/questions/68684079
复制相似问题