2014-02-24 40 views
1

如何添加尊重另一列的黄土平滑作为重量?如何在ggplot2中绘制加权黄土平滑?

比方说,我有以下data.frame:

library(ggplot2) 

    df <- data.frame(x=seq(1:21)) 
    df$y <- df$x*0.3 + 10 
    df$weight <- 10 

    df[6,] <- c(6, 0.1, 1) 
    df[7,] <- c(7, 0.1, 1) 

    df[13,] <- c(13, 0.1, 1) 
    df[14,] <- c(14, 0.1, 1) 

    df[20,] <- c(20, 0.1, 1) 
    df[21,] <- c(21, 0.1, 1) 

    ggplot(data=df, aes(x=x, y=y, size=weight)) + geom_point() + geom_smooth(method=loess, legend=FALSE) 

绘制黄土平滑带来了以下内容:

loess-smoothing without weights

但我想用列权重,使得黄土是相同的,如果每个重量10的点是10倍存在的:

df2 <- subset(df, !(x %in% c(6,7,13,14,20,21))) 
    df2$weight <- 1 

    df3 <- df2 
    for(i in seq(1:9)){ 
     df3 <- rbind(df3, df2) 
    } 
    df3 <- rbind(df3, c(6, 0.1, 1)) 
    df3 <- rbind(df3, c(7, 0.1, 1)) 

    df3 <- rbind(df3, c(13, 0.1, 1)) 
    df3 <- rbind(df3, c(14, 0.1, 1)) 

    df3 <- rbind(df3, c(20, 0.1, 1)) 
    df3 <- rbind(df3, c(21, 0.1, 1)) 

    ggplot(data=df3, aes(x=x, y=y)) + geom_point() + geom_smooth(method=loess, legend=FALSE) 
    # or to demonstrate 
    ggplot(data=df3, aes(x=x, y=y)) + geom_jitter() + geom_smooth(method=loess, legend=FALSE) 

smoothing with weights

我发现了函数黄土的参数权重。但我不知道如何从geom_smooth()调用它。

+0

看到这里最好的答案:HTTP://stackoverflow.com/questions/13904788/how-to-权重平滑的任意因子在ggplot2 – zuuz

回答

6

我想我必须只另一个参数添加到AES:

ggplot(data=df, aes(x=x, y=y, size=weight, weight=weight)) + geom_point() + geom_smooth(method=loess, legend=FALSE) 

enter image description here

+1

http://goo.gl/MTiZVr是一个类似的问题。 – JerryWho