假设我们有函数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()
Run Code Online (Sandbox Code Playgroud)
但是假设我们希望定义一个非连续函数,例如,它y=x^2与 20 到 30、50 到 70 之间的 x 没有值相同。我们如何定义它呢?
我试图将下面的第二行 ( 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()
Run Code Online (Sandbox Code Playgroud)
我将尝试在同一个图上绘制许多非连续函数,因此我怀疑对图本身的任何修改(例如在连续函数的顶部添加元素)都不会很好地扩展。
x对于不属于域的值,您可以将函数的输出替换为 NA 。
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()
Run Code Online (Sandbox Code Playgroud)

由reprex 包于 2021 年 12 月 29 日创建(v2.0.1)