我有以下功能,我想用ggplot绘制:
f(x)= 3/4,x在0和1之间; x为1/4,介于2和3之间; 其他地方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)
Run Code Online (Sandbox Code Playgroud)
但是,这会产生一个只有以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")
Run Code Online (Sandbox Code Playgroud)