2012-05-10 121 views
7

我想向我的圖中添加一個指數(+ power)(趨勢)線。我正在使用ggplot2軟件包。將exp/power趨勢線添加到ggplot

我有這樣的事情(只是有更多的數據):

require(ggplot2) 

df <-read.table("test.csv", header = TRUE, sep = ",") 
df 
    meta temp 
1 1.283 6 
2 0.642 6 
3 1.962 6 
4 8.989 25 
5 8.721 25 
6 12.175 25 
7 11.676 32 
8 12.131 32 
9 11.576 32 

ggplot(df, aes(temp, meta)) + 
    ylab("Metabolism") + xlab("Temperature") + 
    geom_point() + 
    theme_bw() + 
    scale_x_continuous(limits = c(0, 35)) + 
    scale_y_log10() 

我知道,這應該與指數函數來表示 - 所以我的問題是我怎麼能廣告最「指數」擬合?同樣,是否有可能進行動力配合?

stat_smooth()函數是否有這個機會,或者ggplot2包中有其他函數我應該用嗎?

+1

歡迎SO。發佈代碼和示例數據+1。 – Andrie

回答

10

只要通過兩個參數指定了模型擬合作爲參數stat_smooth

  • 方法,例如method="lm"
  • 模型,例如, model = log(y) ~ x

ggplot2首先做的尺度變換,然後擬合模型,所以在您的例子中,你只需要

+ stat_smooth(method="lm") 

添加到您的情節:

library(ggplot2) 
ggplot(df, aes(temp, meta)) + 
    ylab("Metabolism") + xlab("Temperature") + 
    geom_point() + 
    theme_bw() + 
    scale_x_continuous(limits = c(0, 35)) + 
    scale_y_log10() + 
    stat_smooth(method="lm") 

enter image description here


同樣,安裝和繪製功率曲線是改變你的X-規模登錄一樣簡單:

ggplot(df, aes(temp, meta)) + 
    ylab("Metabolism") + xlab("Temperature") + 
    geom_point() + 
    theme_bw() + 
    scale_x_log10() + 
    scale_y_log10() + 
    stat_smooth(method="lm") 

enter image description here

+0

非常感謝!偉大的是,ggplot通過'它自己'找出了當軸改變時使用什麼樣的模型。我有另一個問題,你。是否有可能從適合度中獲得R^2值?在一個正常的線性圖中,我可以使用:fit < - lm(x〜y,data = df),summary(fit)[C(「r.squire」)] – PJensen