【问题标题】:stat_function produces flat line from functionstat_function 从函数产生平线
【发布时间】:2014-10-20 23:24:33
【问题描述】:

我有以下代码:

library("ggplot2")

f <- function(x)
{
    if (x >= 2) {-1 + x + 0.3}
    else {0}    
}

graph <- ggplot(data.frame(x = c(0, 10)), aes(x))
graph <- graph + stat_function(fun=f)
print(graph)

这意外地产生了以下图表:

但是当我单独使用该函数时,结果是预期的:

> f(1)
[1] 0
> 
> f(3)
[1] 2.3
> 
> f(7)
[1] 6.3

怎么会?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    注意以下警告:

    > f(c(0,10))
    [1] 0
    Warning message:
    In if (x >= 2) { :
      the condition has length > 1 and only the first element will be used
    

    c(0,10) 中的第一个元素不大于或等于 2,并且由于您的函数并非旨在对值向量进行操作,因此它仅评估第一个元素并返回单个 0 - 这是您对print(graph) 的呼叫显示了什么。这实际上给出了与上面相同的警告信息:

    > plot(graph)
    Warning message:
    In if (x >= 2) { :
      the condition has length > 1 and only the first element will be used
    

    你只需要向量化你的函数:

    f2 <- function(x)
    {
      ifelse(x>=2,-1+x+.3,0)
    }
    ##
    > f2(c(0,10))
    [1] 0.0 9.3
    ##
    graph2 <- ggplot(data.frame(x = c(0, 10)), aes(x))
    graph2 <- graph2 + stat_function(fun=f2)
    print(graph2)
    

    【讨论】:

    • R 看起来像一门简单的语言,但它有一些疯狂的怪异之处。
    猜你喜欢
    • 2019-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多