[英]Plotting Noncontinuous Function ggplot2
I am attempting to plot this function over the values 0 - 1:我试图在值 0 - 1 上绘制此函数:
dweird <- function(x){
if (x< 0){return(0)}
if (x> 1){return(0)}
if (x >= 0 & x < (1/3)) {return((1))}
if (x >= (1/3) & x < (2/3)){return(3/2)}
if (x >= (2/3) & x <= 1){return((1/2))}
}
and here is the code that I'm using这是我正在使用的代码
library(ggplot2)
ggplot(data.frame(x=c(0, 1)), aes(x)) +
stat_function(fun=function(x) dweird(x), linetype="dotted")
But this returns the error message但这会返回错误消息
Warning message: In if (x >= 0 & x < (1/3)) { : the condition has length > 1 and only the first element will be used警告消息:在 if (x >= 0 & x < (1/3)) { :条件长度 > 1 并且只使用第一个元素
To be clear, the function should plot one straight line at y= 1 from 0-1/3, another at y=1.5 from 1/3-2/3, and another line at 1/2 from 2/3 to 1.为清楚起见,该函数应在 y=1 处从 0-1/3 绘制一条直线,从 1/3-2/3 在 y=1.5 处绘制另一条直线,在 1/2 处从 2/3 到 1 绘制另一条直线。
Any ideas why I'm getting that error message?任何想法为什么我收到该错误消息?
You need to vectorize your function.您需要对函数进行矢量化。 ggplot doesn't expect to evaluate it one point at a time. ggplot 不希望一次评估它一点。 The lazy way is to use vectorize
懒惰的方法是使用vectorize
dweird_v_lazy = Vectorize(dweird)
but the better way is to just code it that way in the first place:但更好的方法是首先以这种方式编码:
dweird_v = function(x) {
ifelse(x < 0, 0,
ifelse(x < 1/3, 1,
ifelse(x < 2/3, 3/2,
ifelse(x < 1, 1/2, 0))))
}
# or, more concisely with `cut`:
dweird_cut = function(x) {
as.numeric(as.character(
cut(x,
breaks = c(-Inf, 0, 1/3, 2/3, 1, Inf),
labels = c(0, 1, 1.5, .5, 0)
)
))
}
Then this will work just fine:然后这将工作得很好:
x = seq(-.2, 1.2, length.out = 15)
dweird_v(x)
[1] 0.0 0.0 0.0 1.0 1.0 1.0 1.5 1.5 1.5 0.5 0.5 0.5 0.0 0.0 0.0
As will your plot:你的情节也一样:
library(ggplot2)
ggplot(data.frame(x=c(0, 1)), aes(x)) +
stat_function(fun= dweird_v, linetype="dotted")
Note that when you're passing a single function to stat_function
, you don't have to turn it into an anonymous function, you can just tell it the name of your function.请注意,当您将单个函数传递给stat_function
,您不必将其转换为匿名函数,您只需告诉它您的函数名称即可。
您需要“矢量化”您的功能:
dweird <- Vectorize(dweird)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.