首页 > 解决方案 > 限制 geom_abline 的范围(slope=somenumber)

问题描述

我正在尝试限制 geom_abline 的范围。在下面的图中,我希望红线在 xvalue 5 处停止,蓝线在值 5 处开始(在图片中,我手动标记了需要删除的段)。

obs:我明白了aesslope不能一起用,但还是把它放在代码里,作为伪代码的一种形式,说明我想让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.

标签: rggplot2abline

解决方案


您可以使用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')

在此处输入图像描述


推荐阅读