2012-11-01 38 views
5

我想繪製一個依賴三個參數的冪律函數:x,agamma。功能如下:在ggplot2中繪製一個多於x的函數作爲參數

powerlaw <- function(x, a, gamma){ 
    a*(x**(-gamma)) 
} 

現在我要繪製,但我無法弄清楚如何specifiy agamma同時告訴R來使用所選擇的範圍x。我嘗試這樣做:

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

但它說

Error in (x^(-gamma)): x is missing 

當然,下面的代碼工作,通過固定agamma

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

任何想法?

回答

3

您需要分別指定參數:

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

詳情請參閱?stat_function

+0

謝謝,這樣做! – networker

1

我只是想創建一個返回功能的data.frame適合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系列獲得更平滑的線):

dat = power_data(seq(1,10,0.01), 1, 1) 
qplot(dat$x, dat$y, geom = "line") 

enter image description here

+0

謝謝保羅,這也是一個有趣的解決方案,我肯定會用於解決不同的問題。對於上述問題,重要的是要有一條平滑的曲線。 ggplot2在提供stat =「function」選項的曲線方面表現出色。 – networker

+0

對於平滑的曲線,您可以使用「x」和較小的dx:'dat = power_data(seq(1,10,0.01),1,1)'。 –

相關問題