2016-11-21 75 views
2

我想用ggplot2將曲線擬合到下面的散點圖。R,ggplot2:將曲線擬合成散點圖

我發現geom_smooth功能,但在嘗試不同的方法和跨度,我似乎從來沒有曲線右...

這是我的散點圖: test1

這是我最好的嘗試: test2

任何人都可以得到更好的曲線適合正確,看上去不那麼威格利?謝謝!

下面爲一個MWE:

my.df <- data.frame(sample=paste("samp",1:60,sep=""), 
        reads=c(523, 536, 1046, 1071, 2092, 2142, 4184, 4283, 8367, 8566, 16734, 17132, 33467, 34264, 66934, 68528, 133867, 137056, 267733, 274112, 409, 439, 818, 877, 1635, 1754, 3269, 3508, 6538, 7015, 13075, 14030, 26149, 28060, 52297, 56120, 104594, 112240, 209188, 224479, 374, 463, 748, 925, 1496, 1850, 2991, 3699, 5982, 7397, 11963, 14794, 23925, 29587, 47850, 59174, 95699, 118347, 191397, 236694), 
        number=c(17, 14, 51, 45, 136, 130, 326, 333, 742, 738, 1637, 1654, 3472, 3619, 7035, 7444, 13133, 13713, 21167, 21535, 11, 22, 30, 44, 108, 137, 292, 349, 739, 853, 1605, 1832, 3099, 3565, 5287, 5910, 7832, 8583, 10429, 11240, 21, 43, 82, 124, 208, 296, 421, 568, 753, 908, 1127, 1281, 1448, 1608, 1723, 1854, 1964, 2064, 2156, 2259), 
        condition=rep(paste("cond",1:3,sep=""), each=20)) 

png(filename="TEST1.png", height=800, width=1000) 
print(#or ggsave() 
ggplot(data=my.df, aes(x=reads, y=log2(number+1), group=condition, color=condition)) + 
    geom_point() 
) 
dev.off() 

png(filename="TEST2.png", height=800, width=1000) 
print(#or ggsave() 
ggplot(data=my.df, aes(x=reads, y=log2(number+1), group=condition, color=condition)) + 
    geom_point() + 
    geom_smooth(se=FALSE, method="loess", span=0.5) 
) 
dev.off() 

回答

6

這是一個很廣泛的問題,因爲你正在有效地尋找與變化較小(更偏向),其中有很多的典範。這裏有一個:

ggplot(data = my.df, 
     aes(x = reads, y = log2(number + 1), color = condition)) + 
    geom_point() + 
    geom_smooth(se = FALSE, method = "gam", formula = y ~ s(log(x))) 

log gam model

有關文檔,看?mgcv::gam或建模一個合適的文本。根據您的使用情況,將模型設置爲ggplot之外可能更有意義。