繁体   English   中英

绘制非连续函数 ggplot2

[英]Plotting Noncontinuous Function ggplot2

我试图在值 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 并且只使用第一个元素

为清楚起见,该函数应在 y=1 处从 0-1/3 绘制一条直线,从 1/3-2/3 在 y=1.5 处绘制另一条直线,在 1/2 处从 2/3 到 1 绘制另一条直线。

任何想法为什么我收到该错误消息?

您需要对函数进行矢量化。 ggplot 不希望一次评估它一点。 懒惰的方法是使用vectorize

dweird_v_lazy = Vectorize(dweird)

但更好的方法是首先以这种方式编码:

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 ,您不必将其转换为匿名函数,您只需告诉它您的函数名称即可。

您需要“矢量化”您的功能:

dweird <- Vectorize(dweird)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM