2012-09-20 18 views
1

在GGPLOT2我嘗試,我只是不能出於某種原因一件簡單的事情平均分。我調整了數據框中的平均值和SE,並想繪製平均值,誤差線,然後用平均值連接平均值。下面的代碼和錯誤(它除了一切手段與geom_line(與RCookbook工作連接:連接的誤差條

library(ggplot2) 
#data set 
data1 <- structure(list(group = structure(1:3, .Label = c("1", "2", "3" 
), class = "factor"), estimate = c(55.7466654122763, 65.0480954172939, 
61.9552391704298), SE = c(2.33944612149257, 2.33243565412438, 
2.33754952927041), t.ratio = c(23.8290016171476, 27.8884844271143, 
26.5043535525714)), .Names = c("group", "estimate", "SE", "t.ratio" 
), row.names = c(NA, 3L), class = "data.frame") 

#the attempted plot 
pd <- position_dodge(.1) 
ggplot(data1, aes(x=group, y=estimate, group=group)) + 
    geom_errorbar(aes(ymin=estimate-SE, ymax=estimate+SE), 
     colour="black", width=.1, position=pd) + 
    geom_line(data=data1, aes(x=group, y=estimate)) + 
    geom_point(position=pd, size=4) 

錯誤:

ymax not defined: adjusting position using y instead 
geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic? 

回答

3

如果通過group的ggplot調用中刪除分組和調用geom_line內設置x = as.numeric(group)時,它的工作原理。

而且,你不需要重新參考data1geom_line

ggplot(data1, aes(x=group, y=estimate)) + 
    geom_errorbar(aes(ymin=estimate-SE, ymax=estimate+SE), 
    colour="black", width=.1, position=pd) + 
    geom_line(aes(x=as.numeric(group), y=estimate)) + 
    geom_point(position=pd, size=4) 

enter image description here

如果group通過group,那麼你只有一個geom_line創造價值從線,因此錯誤消息。如果ggplot正在考慮xy映射變量的一個因素髮生同樣的錯誤 - 這是因爲,如果你編寫一個變量作爲一個因子R(和ggplot)會考慮他們的獨立團體,並沒有連接點 - 這是合理的默認behaiviour。

編輯 - 以字母因素標籤

這將字母因素標籤因工作方式的因素是由R內部編碼(即as.numeric(因子)返回的數字不是因子標籤)

ie.e

更改組到abc

levels(data1[['group']]) <- letters[1:3] 
ggplot(data1, aes(x=group, y=estimate)) + 
    geom_errorbar(aes(ymin=estimate-SE, ymax=estimate+SE), 
    colour="black", width=.1, position=pd) + 
    geom_line(aes(x=as.numeric(group), y=estimate)) + 
    geom_point(position=pd, size=4) 

enter image description here

+0

謝謝MNEL。這種情況下的團體恰好可以解決問題,但如果他們是A組,B組和C組呢?此外,我知道我沒有重新應用數據geom_line但呼籲瘋狂的想法:) –

+0

可能有人解釋爲什麼我需要轉換爲數字或使用組=「所有」招的理由絕望的措施設置? –

+0

工作良好---因爲'R'代碼因素的方式 – mnel

2

作爲替代MNEL的回答,您可以創建一個新的變量,讓你有一列,所有3組具有相同的價值:

data1$all <- "All" 

然後用其作爲group審美爲您行:

ggplot(data1, aes(x=group, y=estimate)) + 
    geom_errorbar(aes(ymin=estimate-SE, ymax=estimate+SE), 
     colour="black", width=.1, position=pd) + 
    geom_line(aes(x=group, y=estimate, group=all)) + 
    geom_point(position=pd, size=4) 

MNEL的答案可能是更優雅,但是這可能會更好地工作,如果組不是數字,不能轉化爲numeri c直截了當。

+1

'as。數字技巧應該與任何因素一起工作,因爲'R'處理因素的方式(帶有標籤的整數) – mnel

+0

啊好的呼叫。 –

+0

當數據框已經包含像「ALL」這樣的值時,我更喜歡這種分組方法。爲簡單起見+1。 – blehman

1

你也可以看看第二個答案,這SO Question如果你向一個更爲全面地落實工作,這可能爲您節省一些時間。