2013-04-17 45 views
3

聚合因子平穩,我想用格子來創建多面板散點圖,並添加通過每個面板使用聚合因子流暢的線條,這裏是一個虛擬的數據框多面板與晶格

x <- rep(1:10, 4) 
a <- as.factor(rep(1:4, 10)) 
b <- as.factor(sort(rep(1:2, 20))) 
y <- rep(NA, 80) 
df <- data.frame(x, y, a, b) 
df$y[df$b=="1"] <- df$x[df$b=="1"]+df$x[df$b=="1"]^0.5 
df$y[df$b=="2"] <- df$x[df$b=="2"]+df$x[df$b=="2"]^1 
df$y[df$b=="3"] <- df$x[df$b=="3"]+df$x[df$b=="3"]^2 
for(i in 1:80) df$y[i] <- df$y[i]+rnorm(1, 0, 10) 

我這個嘗試:

library(lattice)  
xyplot(y ~ x|a, data = df, groups = b, type = "b", 
         panel = function(x, y,...){ 
         panel.smooth(x, y, ...) 
         panel.xyplot(x, y, ...) 
         }) 

但似乎沒有工作,我不明白爲什麼,肯定是我失蹤的東西。 但是,我還有一個問題,那就是我需要改變一些平滑參數(跨度和度)。我找到了一種方法做了卡中的跨驗證了在線(?是不是正確的引用其他用戶以這種方式工作),那就是:

my.panel.loess <- function(x, y, span = 2/3, degree = 0.5, ...) { 
    loess.fit <- loess.smooth(x, y, span = span, dgree = degree) 
    panel.lines(loess.fit$x, loess.fit$y, ...) 
    panel.xyplot(x, y, ...)} 

xyplot(y ~ x|a, data = df, groups = b, type = "b", 
        panel=function(...) 
        panel.superpose(panel.groups=my.panel.loess, ...)) 

,但我不能讓它繪製的線黃土更平滑,並指向原始數據點。我試圖在自定義函數中添加參數類型,但lattice不喜歡多重參數。任何建議?

回答

3

我經常發現latticeExtra(及其layer()as.layer()和重載+運營商)的設置有很大幫助像您一樣的:

library(latticeExtra) 
my.panel.loess <- function(x, y, span = 2/3, degree = 0.5, ...) { 
    loess.fit <- loess.smooth(x, y, span = span, dgree = degree) 
    panel.lines(loess.fit$x, loess.fit$y, ...) 
} 

## A plot with the smoothing lines 
a <- xyplot(y ~ x|a, data = df, groups = b, type="l", 
      panel=function(...) panel.superpose(panel.groups=my.panel.loess,...)) 
## A plot with the points 
b <- xyplot(y ~ x|a, data=df, groups=b) 

## Both together 
plot(a+b) 

enter image description here

+0

謝謝Josh,我需要探索latticeEx深度更大。 – matteo

5

或不latticeExtra,只需:

xyplot(y~ x|a, data = df, groups = b, type = c("p", "smooth"))