I have the following function, which I would like to plot using ggplot:
我有下面的函数,我想用ggplot来绘图:
f(x) = 3/4 for x between 0 and 1; 1/4 for x between 2 and 3; and 0 elsewhere.
f(x) = 3/4, x在0和1之间;1/4的x在2到3之间;和0。
I have come up with the following R code:
我已经提出了以下的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)
However, this results in a plot with only a horizontal line centered on 0. What have I done wrong?
然而,这只会导致一个以0为中心的水平线。我做错了什么?
2 个解决方案
#1
5
The function should be "vectorized", i.e., accept a vector as argument.
函数应该是“向量化的”,即。,接受一个向量作为参数。
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")
#2
0
I think this is another place where either switch
could be used to great effect, or something along the lines of ysteps <- c(.75,.25,0)
xsteps <- c(1,2,3)
y <- ysteps[which(x >= xsteps)]
我认为这是另一个开关可以用来产生巨大影响的地方,或者类似于ysteps <- c(.75,.25,0) xsteps <- c(1,2,3) y <- ysteps (x >= xsteps)的地方。
Please feel free to edit this so it's correct -- my brain is slow and I don't have R available right now.
请随意编辑,这是正确的,我的大脑是慢的,我现在没有R。
#1
5
The function should be "vectorized", i.e., accept a vector as argument.
函数应该是“向量化的”,即。,接受一个向量作为参数。
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")
#2
0
I think this is another place where either switch
could be used to great effect, or something along the lines of ysteps <- c(.75,.25,0)
xsteps <- c(1,2,3)
y <- ysteps[which(x >= xsteps)]
我认为这是另一个开关可以用来产生巨大影响的地方,或者类似于ysteps <- c(.75,.25,0) xsteps <- c(1,2,3) y <- ysteps (x >= xsteps)的地方。
Please feel free to edit this so it's correct -- my brain is slow and I don't have R available right now.
请随意编辑,这是正确的,我的大脑是慢的,我现在没有R。