绘制非连续函数ggplot2 [英] Plotting Noncontinuous Function ggplot2
问题描述
我正在尝试将此函数绘制在值0-1上:
I am attempting to plot this function over the values 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))}
}
这是我正在使用的代码
library(ggplot2)
ggplot(data.frame(x=c(0, 1)), aes(x)) +
stat_function(fun=function(x) dweird(x), linetype="dotted")
但这会返回错误消息
警告信息:如果if(x> = 0& x<(1/3)){:条件的长度> 1,并且只会使用第一个元素
Warning message: In if (x >= 0 & x < (1/3)) { : the condition has length > 1 and only the first element will be used
为清楚起见,该函数应绘制一条直线,其中y = 1从0-1/3开始,另一条直线在y = 1.5从1/3-2/3开始,另一条直线在1/2从2/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.
我为什么收到该错误消息的任何想法?
Any ideas why I'm getting that error message?
推荐答案
您需要向量化您的函数.ggplot不能一次评估一个点.懒惰的方法是使用 vectorize
You need to vectorize your function. ggplot doesn't expect to evaluate it one point at a time. The lazy way is to use 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)
)
))
}
然后这将很好地工作:
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
您的情节也会如此:
library(ggplot2)
ggplot(data.frame(x=c(0, 1)), aes(x)) +
stat_function(fun= dweird_v, linetype="dotted")
请注意,当您将单个函数传递给 stat_function
时,不必将其转换为匿名函数,只需告诉它函数的名称即可.
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.
这篇关于绘制非连续函数ggplot2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!