2017-07-02 101 views
0

我用ggplot2做了一個簡單的barplot,比較了2種昆蟲的雄性和雌性的平均壽命(年齡)。 我的代碼看起來像這樣,以「集」是,好了,我的數據集...如何將SE錯誤欄添加到ggplot2中的barplot中?

gplot(dataset, aes(Species, Age, fill=Sex))+ 
stat_summary(fun.y = mean, geom = "bar", position = "dodge")+ 
scale_fill_manual(values = c("Grey25", "Grey"))+ 
theme(legend.title = element_blank())+ 
scale_y_continuous(limits = c(0,15)) 

我用下面的代碼手動輸入的平均值±SE的值設置爲限制嘗試錯誤欄。爲了簡單起見,我們假設物種1的平均值爲10,SE = 0.5。

geom_errorbar(aes(ymin=9.5, ymax=10.5),width=.2,position=position_dodge(.9)) 

這段代碼確實有效,但它爲我的陰謀中的每個欄設置了相同的誤差線。

如何在我的圖中爲每個條添加等於相應SE的誤差線?

我對ggplot和R相當新,所以任何幫助/建議是值得歡迎的。

+0

您需要先計算誤差以及用於各條,並將它們變異成你的數據集。然後將'ymin'和'ymax'設置爲這些列。 – Masoud

+0

這可能對你有所幫助。 http://environmentalcomputing.net/plotting-with-ggplot-bar-plots-with-error-bars/ – Masoud

+0

我似乎無法讓'ymin'和'ymax'正常工作。 我跟着你提供的鏈接,用虹膜數據嘗試了這個例子,那也不管用......我無法通過'group_by(Species)'。 顯示以下錯誤消息:UseMethod(「group_by_」)中的錯誤:沒有將'group_by_'的適用方法應用於類「factor」的對象。 –

回答

2

你並不需要更多的比stat_summary(geom = "errorbar", fun.data = mean_se, position = "dodge")添加到您的情節:

library(ggplot2) 

ggplot(diamonds, aes(cut, price, fill = color)) + 
    stat_summary(geom = "bar", fun.y = mean, position = "dodge") + 
    stat_summary(geom = "errorbar", fun.data = mean_se, position = "dodge") 

如果你喜歡預先計算的值,你可以做這樣的:

library(tidyverse) 
pdata <- diamonds %>% 
    group_by(cut, color) %>% 
    summarise(new = list(mean_se(price))) %>% 
    unnest(new) 


pdata %>% 
    ggplot(aes(cut, y = y, fill = color)) + 
    geom_col(position = "dodge") + 
    geom_errorbar(aes(ymin = ymin, ymax = ymax), position = "dodge") 
+0

您建議我添加的代碼行已經工作。謝謝。 –

0

您可以使用geom_errorbar幾何圖形在您的條形圖上添加一個錯誤條。

您需要提供yminymax,因此您需要手動計算它。

geom_errorbar幫助頁面:

p + geom_errorbar(aes(ymin = lower, ymax = upper), width = 0.2) 

科林