r - 限制 geom_abline 的范围(slope=somenumber)
问题描述
我正在尝试限制 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.
解决方案
您可以使用geom_function()
代替来执行此操作geom_abline()
,并指定一个矢量化函数。如果您不确定“向量化”函数是什么意思,那么我们希望函数NA
在 x 值在我们不希望该行出现的范围内时返回,否则返回该行。为了像这样沿着每个 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')
推荐阅读
- php - OPENDIR 来自 $_REQUEST 的值
- azure - IotHubClientTransientException:发生瞬态错误,请重试
- java - 使用 StandardXYToolTipGenerator 格式化工具提示值
- javascript - createStore 不会从初始状态更改为 Action 证明值
- cordova - 有没有办法使用 Ionic 3 在浏览器中捕获音频
- spring - 在 Spring AOP 中使用 Aspects 条件执行方法
- php - htmlentities 无法将 HTML 实体转换为字符
- cryptography - 无法创建名称为“http://www.w3.org/2000/09/xmldsig#hmac-sha1”的算法
- c# - Activator.CreateInstance 期间的 MissingMethodException
- excel - 将散点图上的点与系列间隙连接起来