Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw a function in ggplot2 with more than x as parameter

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?

like image 890
networker Avatar asked Nov 01 '12 10:11

networker


2 Answers

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.

like image 184
csgillespie Avatar answered Oct 21 '22 15:10

csgillespie


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")

enter image description here

like image 21
Paul Hiemstra Avatar answered Oct 21 '22 14:10

Paul Hiemstra