【问题标题】:Show raw values and weighted mean for each factor level in ggplot2在 ggplot2 中显示每个因子水平的原始值和加权平均值
【发布时间】:2013-04-05 13:54:21
【问题描述】:

我试图为不同的因子水平(样本)和加权平均值(权重=覆盖)显示一个变量(等位基因特定表达式)。

我做了一些示例数据:

set.seed(2)
x <- sample(c("A","B","C"), 100, replace=T)
y <- rnorm(100)
w <- ceiling(rnorm(100,200,200))
df <- data.frame(x, y, w)

library(ggplot2)
ggplot(df, aes(x=factor(x), y=y, weight=w)) +
  geom_point(aes(size=w)) +
  stat_summary(fun.y=mean, colour="red", geom="point", size=5)

(我也尝试发布情节 - 但我还没有足够的积分)。

这很好用 - 但它显示了未加权的平均值......

library(plyr)
means <- ddply(df, "x", function(x) data.frame(wm=weighted.mean(x$y, x$w),
                                               m=mean(x$y)))
means

 x          wm           m
1 A  0.00878432  0.11027454
2 B -0.07283770 -0.13605530
3 C -0.14233389  0.08116117

所以 - 我只是想将“wm”值显示为红点 - 使用 ggplot2.我认为它必须正确使用“weight=..” - 但我现在放弃了......

我真的希望有人可以提供帮助。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    我将首先使用meanweighted mean 创建summary data.frame,如下所示:

    require(plyr)
    dd <- ddply(df, .(x), summarise, m=mean(y), wm=weighted.mean(y, w))
    

    然后,我将通过加载这些数据来显示平均值和加权平均值。

    require(reshape2) # for melt
    require(ggplot2)
    ggplot() + geom_point(data = df, aes(x=factor(x), y=y, size=w)) + 
              geom_point(data = melt(dd, id.var="x"), 
              aes(x=x, y=value, colour=variable), size=5) 
    
    # if you want to remove the legend "variable"
    scale_colour_discrete(breaks=NULL)
    

    您可能需要考虑使用scale_size_area() 为价值分配提供更好/无偏见的大小。

    【讨论】:

    • 谢谢你——你拯救了我的周末!
    • 你好。对 SO 来说并不是很新 - 但主要是阅读答案(因为我所在地区的大多数问题之前至少被问过一次;))。我试图立即接受,但被系统强制等待了一段时间。无论如何:非常感谢您的快速帮助。
    猜你喜欢
    • 2012-02-06
    • 1970-01-01
    • 1970-01-01
    • 2018-11-16
    • 2014-09-11
    • 2013-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多