I would like to draw a power-law function which depends on three parameters: x, a, and gamma. The function looks like this:
powerlaw <- function(x, a, gamma){
   a*(x**(-gamma))
}
Now I want to plot this but I cannot figure out how to specifiy a and gamma while telling R to use the chosen range for x. I tried this:
require(ggplot2)
qplot(c(1,10), stat="function", fun=powerlaw(x, a=1, gamma=1), geom="line")
but it says
Error in (x^(-gamma)): x is missing  
Of course, the following code works by fixing a and gamma:
powerlaw1 <- function(x){
   1*(x**(-1))
}
qplot(c(1,10), stat="function", fun=powerlaw1, geom="line")
Any ideas?
You need to specify the arguments separately:
qplot(x=c(1,10), stat="function", 
      fun=powerlaw, geom="line", 
      arg=list(a=1, gamma=1))
See ?stat_function for more details.
I would just create a function which returns a data.frame appropriate for 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
and make a plot (note that I use a more tightly spaced x series to get a smoother line):
dat = power_data(seq(1,10,0.01), 1, 1)
qplot(dat$x, dat$y, geom = "line")

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With