我有以下函数,我想使用 ggplot 绘制它:

f(x) = 3/4 对于介于 0 和 1 之间的 x; 1/4 对于 2 和 3 之间的 x;其他地方为 0。

我想出了以下 R 代码:

eq<-function(x) {
    if(x>=0 && x<=1) {
        y<-3/4
    } else if(x>=2 && x<=3) {
        y<-1/4
    } else {
    y<-0
    }
return(y)
}

library(ggplot2)

ggplot(data.frame(x=c(-5,5)), aes(x)) + stat_function(fun=eq)

但是,这会导致绘图中只有一条以 0 为中心的水平线。我做错了什么?

最佳答案

该函数应该是“矢量化的”,即
接受一个向量作为参数。

eq <- function(x)
  ifelse( x>=0 & x<=1, 3/4,
  ifelse( x>=2 & x<=3, 1/4, 0 ))
ggplot(data.frame(x=c(-5,5)), aes(x)) +
  stat_function(fun=eq, geom="step")

关于r - 在 ggplot2 中绘制离散(或不连续)函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9330040/

10-12 00:27
查看更多