2016-03-03 19 views
2

我有一組由多個變量表徵的記錄,標記爲「in」或「out」。我想統計所有記錄的統計數據和標記爲「in」的統計數據,同時繪製每個點只顯示一次,用彩色顯示哪些是「in」或「out」。我怎樣才能做到這一點?我只知道如何繪製「in」和「out」組的彙總統計數據(見下面的代碼),而不是「in」和「all」。 如果圖例解釋了點的顏色(如我的插圖)以及錯誤欄的顏色,那麼這將是一個加號。R和ggplot2:爲重疊範圍創建摘要統計

library(data.table) 
library(ggplot2) 
d = data.table(v1 = rnorm(10, 0, 1), 
       v2 = rnorm(10, 1, 2), 
       g = as.factor(c(rep('in', 7), rep('out', 3)))) 
m = melt(d, c('g')) 
print(ggplot(m, aes(x = variable, y = value, colour = g)) + 
     facet_wrap(~variable, scales = "free") + 
     geom_jitter(position = position_jitter(height = 0, width = 0.2)) + 
     stat_summary(fun.data = mean_se, geom = "errorbar", width = 0.25)) 

Plot with summary statistics for "in" and "out"

+0

你是什麼意思的「情節彙總統計?」你想要的最終情節是什麼樣的? – MrFlick

+0

通過彙總統計,我指的是「stat_summary」提供的功能(請參閱示例代碼)。最後的情節看起來像我提供的,除了你會有「in」和「all」而不是「in」和「out」(全部是指所有行,「out」是指那些g是「出」)。 – jciloa

+0

你的代碼給出'錯誤:無法找到功能「融化」'。這是因爲,儘管'melt'在data.table中,您還需要加載package reshape2(根據「?melt」)。 – RHA

回答

3

如果你想和退出點來展示,但errorbars在總,你應該將你的顏色的命令和添加不同stat_summary在所有:

library(data.table) 
library(reshape2) #needed because data.table::melt will only work with reshape2 
library(ggplot2) 
d <- data.table(v1 = rnorm(10, 0, 1), 
       v2 = rnorm(10, 1, 2), 
       g = as.factor(c(rep('in', 7), rep('out', 3)))) 

m <- melt(d, c('g')) 

ggplot(m, aes(x = variable, y = value)) + # removed colour here 
     facet_wrap(~variable, scales = "free") + 
     geom_jitter(aes(colour = g), position = position_jitter(height = 0, width = 0.2)) + #added color here 
     stat_summary(fun.data = mean_se, geom = "errorbar", width = 0.25) + #errorbars for total observations 
     stat_summary(data=m[m$g == "in",], fun.data = mean_se, geom = "errorbar", width = 0.25, colour = 2) # errorbars for "in" group 

enter image description here

+0

感謝您的幫助!是的,這是有效的 - 除了現在有兩個點標記爲「in」的行。 – jciloa

+0

@ jciloa可能與數據複製有關。我會稍後再研究它,現在有點忙...... – RHA

+0

我認爲數據複製是正確的。只有這種方法需要在「所有」中存在「入」點,這對繪製總結統計數據非常有用,但這些點將被繪製兩次(並且由於附加的抖動,通常會看到兩次)。 – jciloa