代码之家  ›  专栏  ›  技术社区  ›  stevec Zxeenu

如何定义(和绘制)R中的非连续函数?

  •  2
  • stevec Zxeenu  · 技术社区  · 3 年前

    y = x^2 ,我们可以策划这个 函数从x=0到x=100,如下所示:

    library("ggplot2")
    eq = function(x){x^2}
    ggplot(data.frame(x=c(1, 100)), aes(x=x)) + 
      stat_function(fun=eq) +
      theme_void()
    

    ggplot2 plot of a continuous function

    但是假设我们想要定义一个 连续函数,比如说,它与 y=x^2 但是x在20到30之间,以及50到70之间没有值。我们如何定义它?

    上下文

    我正在尝试替换下面的第二行( eq = function(x){x*x}

    library("ggplot2")
    eq = function(x){x*x} # CHANGE ONLY THIS LINE (IF POSSIBLE)
    ggplot(data.frame(x=c(1, 100)), aes(x=x)) + 
      stat_function(fun=eq) +
      theme_void()
    

    我会设法策划 许多的

    1 回复  |  直到 3 年前
        1
  •  5
  •   teunbrand    3 年前

    对于的值,您可以使用NAs替换函数的输出 x 不属于您的域的一部分。

    library(ggplot2)
    
    eq <- function(x) {
      ans <- x * x
      ans[x >= 20 & x <= 30] <- NA
      ans[x >= 50 & x <= 70] <- NA
      ans
    }
    
    ggplot(data.frame(x = c(1, 100)), aes(x)) +
      stat_function(fun = eq) +
      theme_void()
    

    于2021年12月29日由 reprex package (v2.0.1)