stat_function从函数产生扁平线 [英] stat_function produces flat line from function

查看:101
本文介绍了stat_function从函数产生扁平线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

  library(ggplot2)

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

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

意外地产生了以下图表:


但是,当我使用函数本身的结果是预期的:

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

怎么样?

解决方案

请注意以下警告:

 > f(c(0,10))
[1] 0
警告信息:
在if(x> = 2){:
中,条件长度> 1,只有第一个元素会被使用

c 0,10)不大于或等于2,并且由于你的函数没有被设计为对一个向量值进行操作,所以它只评估第一个元素并返回一个 0 - 这是您对 print(图形)的调用显示。这实际上给出了与上面相同的警告信息:

 >情节(图)
警告信息:
在if(x> = 2){:
中,条件长度> 1,并且只有第一个元素将被使用

您只需要矢量化您的函数:

  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)


I have the following code:

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)

That unexpectedly produces the following graph:

But when I use the function on its own the result is the expected:

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

How come?

解决方案

Note the following warning:

> 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

The first element in c(0,10) is not greater than or equal to 2, and since your function was not designed to operate on a vector of values, it only evaluated the first element and returned a single 0 - which is what your call to print(graph) displays. This actually gave the same warning message as above:

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

You just need to vectorize your function:

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)

这篇关于stat_function从函数产生扁平线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆