无法在ggplot2

时间:2016-02-18 03:04:25

标签: r ggplot2

我正在尝试使用Nilakantha's infinite series评估pi π= 3 + 4 /(2 * 3 * 4) - 4 /(4 * 5 * 6)+4 /(6 * 7 * 8) - 4 /(8 * 9 * 10)+ 4 /(10 * 11 * 12) - 4 /(12 * 13 * 14)....并且无法使stat_function工作 我写了以下函数:

  est.pi <- function(n){
  pi <- 3
  for (i in 1:n) {
    den <- (2*i)*(2*i+1)*(2*i+2)
    if (i %% 2 == 0) {
      pi <- pi - 4/den}
    else {
      pi <- pi + 4/den}
  }
  return(pi)
  }

效果很好:

> options(digits = 10)
> est.pi(10000)
[1] 3.141592654

但是当我尝试在ggplot2中绘制它时,stat_function()仅评估第一个参数:

n <- 10
s.x <- scale_x_continuous(breaks=seq(1,10))  
s.y <- scale_y_continuous(limits=c(3.13,3.17), breaks=seq(3.13, 3.17, 0.01))
ggplot(data.frame(x = 1:n), aes(x)) + stat_function(fun = est.pi) + s.x + s.y

enter image description here

但是,如果我手动创建一个数据框,它会按预期运行并在3.14159附近很好地收敛:

pi. <- data.frame(x = 1:n)
pi. <- within (pi., pi.est <- sapply (x, est.pi))
ggplot(pi., aes(x=x, y=pi.est)) + geom_line() + s.x + s.y

enter image description here

如何让stat_function动态评估x向量?感谢。

0 个答案:

没有答案