2010-01-22 64 views
5

我有一個幾乎箱線圖一樣抖動情節:添加分組標籤抖動情節GGPLOT2

dt <- rbind(se,cb,cb.se) 
qplot(ds, size, data=dt, geom="jitter", colour=root, facets = test ~ .) 

plot http://i50.tinypic.com/1zbfjih.png

我很想把一個彙總標籤爲每個組在中間情節 - 例如規模總計在這裏:

aggregate(list(size=dt$size), list(dt$ds, dt$test), sum) 

    Group.1 Group.2 size 
1  b217  se 9847 
2  c10  se 97296 
3  c613  se 21633 
4  c7  se 207540 
... 

我使用+ geom_text(aes(x=ds, y=128, label=sum(size)), size=2)添加標籤試過,但我得到的每一個位置同一個標籤 - 我怎麼能得到的總和只是那部分數據?

編輯: 在此處,我在現在 - 也許我只是在錯誤的方向

data <- rbind(se,cb,cb.se) 
labels <-ddply(data, c("ds", "test"), function(df) sum(df$size)) 
ggplot(data=data, aes(x=ds)) + 
    geom_jitter(aes(y=size, colour=root)) + 
    geom_text(data=labels, aes(x=ds, y=600, label=V1), size=3) + 
    facet_wrap(test ~ .) 

這個代碼不工作 - 我得到一個錯誤undefined columns selected某處... 。也許這是因爲多個data=部分?

+0

從快速閱讀,該代碼看起來好像沒什麼問題。沒有可重複的例子,很難說更多。 – hadley 2010-01-23 01:52:35

+1

我已經發布了一個解決方案。不幸的是,由於您沒有提供樣本數據,我不得不重新創建隨機數據。這意味着解決方案可能會或可能不會反映您自己的數據。爲了將來的參考,如果您只是對問題做一個簡單的例子並粘貼一些我們可以用來重現問題的示例數據,您將吸引更多的答案。無論如何,我希望它有幫助。 – Andrie 2011-07-12 06:23:06

回答

6

由於您沒有提供樣本數據,因此我將演示一個使用隨機數據的解決方案。

set.seed(1) 
n <- 100 
dat <- data.frame(
    ds = sample(paste("x", 1:8, sep=""), n, replace=TRUE), 
    size = runif(n, 0, 250), 
    root = sample(c(TRUE, FALSE), n, replace=TRUE), 
    test = sample(c("se", "cb", "cb.se"), n, replace=TRUE) 
) 


head(dat) 
    ds  size root test 
1 x3 163.68098 TRUE cb.se 
2 x3 88.29932 TRUE se 
3 x5 67.56504 FALSE cb 
4 x8 248.17102 TRUE cb 
5 x2 158.37332 TRUE cb 
6 x8 53.30203 FALSE cb.se 

p <- ggplot(dat, aes(x=ds, y=size)) + 
    geom_jitter(aes(colour=root)) + 
    facet_grid(test~.) 

創建包含標籤數據的數據幀。請注意使用summarize。這告訴ddply創建一個新列data.frame

labels <- ddply(dat, .(ds, test), summarize, size=round(sum(size), 0)) 
head(labels) 
    ds test size 
1 x1 cb 193 
2 x1 cb.se 615 
3 x1 se 274 
4 x2 cb 272 
5 x2 cb.se 341 
6 x2 se 1012 

p + geom_text(aes(x=ds, label=size, y=128), data=labels, size=2) 

enter image description here

+0

這看起來完全像我所需要的。謝謝! – Thelema 2011-07-13 11:49:42

+1

@Thelema,很高興我能幫上忙。 (記得分配賞金,因爲這不會自動發生) – Andrie 2011-07-13 12:10:28

+0

當之無愧。不錯。並快速:) – 2011-07-13 15:23:32