R 在ggplot2中绘制一个参数大于x的函数

R 在ggplot2中绘制一个参数大于x的函数,r,function,ggplot2,R,Function,Ggplot2,我想画一个幂律函数,它取决于三个参数:x,a,和gamma。函数如下所示: powerlaw <- function(x, a, gamma){ a*(x**(-gamma)) } 但是它说 Error in (x^(-gamma)): x is missing 当然,下面的代码通过固定a和gamma来工作: powerlaw1 <- function(x){ 1*(x**(-1)) } qplot(c(1,10), stat="function", fun=po

我想画一个幂律函数,它取决于三个参数:
x
a
,和
gamma
。函数如下所示:

powerlaw <- function(x, a, gamma){
   a*(x**(-gamma))
}
但是它说

Error in (x^(-gamma)): x is missing  
当然,下面的代码通过固定
a
gamma
来工作:

powerlaw1 <- function(x){
   1*(x**(-1))
}
qplot(c(1,10), stat="function", fun=powerlaw1, geom="line")

powerlaw1您需要单独指定参数:

qplot(x=c(1,10), stat="function", 
      fun=powerlaw, geom="line", 
      arg=list(a=1, gamma=1))

有关更多详细信息,请参见统计函数。

我只想创建一个函数,该函数返回适合于
ggplot2
数据帧:

power_data = function(x, a, gamma) {
   return(data.frame(x = x, y = a * (x**(-gamma))))
}

> power_data(1:10, 1, 1)                                           
    x         y                                                    
1   1 1.0000000                                                    
2   2 0.5000000                                                    
3   3 0.3333333                                                    
4   4 0.2500000                                                    
5   5 0.2000000                                                    
6   6 0.1666667                                                    
7   7 0.1428571                                                    
8   8 0.1250000                                                    
9   9 0.1111111
10 10 0.1000000
并绘制一个图(注意,我使用了一个间隔更紧的
x
序列来获得一条更平滑的线):


谢谢Paul,这也是一个有趣的解决方案,我肯定会用它来解决另一个问题。对于上述问题,重要的是要有一条平滑的曲线。ggplot2在使用stat=“function”选项提供此类曲线方面做得非常出色。对于平滑曲线,您只需使用带有较小dx的
x
dat=power\u数据(seq(1,10,0.01),1,1)
power_data = function(x, a, gamma) {
   return(data.frame(x = x, y = a * (x**(-gamma))))
}

> power_data(1:10, 1, 1)                                           
    x         y                                                    
1   1 1.0000000                                                    
2   2 0.5000000                                                    
3   3 0.3333333                                                    
4   4 0.2500000                                                    
5   5 0.2000000                                                    
6   6 0.1666667                                                    
7   7 0.1428571                                                    
8   8 0.1250000                                                    
9   9 0.1111111
10 10 0.1000000
dat = power_data(seq(1,10,0.01), 1, 1)
qplot(dat$x, dat$y, geom = "line")