[英]Adding error bars to ggplot2 bar plot after group by in dplyr
我在 R 中有以下數據。
oligo condition score
REF Sample 27.827
REF Sample 24.622
REF Sample 31.042
REF Competitor 21.066
REF Competitor 18.413
REF Competitor 36.164
ALT Sample 75.465
ALT Sample 57.058
ALT Sample 66.408
ALT Competitor 35.420
ALT Competitor 17.652
ALT Competitor 21.466
我已經對此進行了修改,並使用 dplyr 中的group_by
和summarise
函數計算了每個條件的分數的平均值。
emsa_test <- emsa_1 %>%
group_by(oligo,condition) %>%
summarise_all(mean)
創建此表。
oligo condition score
ALT Competitor 24.84600
ALT Sample 66.31033
REF Competitor 25.21433
REF Sample 27.83033
然后我使用 ggplot2 繪制了這個圖。
ggplot(emsa_test, aes(oligo, score)) +
geom_bar(aes(fill = condition),
width = 0.4, position = position_dodge(width=0.5), color = "black", stat="identity", size=.3) +
theme_bw() +
ggtitle("CEBP\u03b1") +
theme(plot.title = element_text(size = 40, face = "bold", hjust = 0.5)) +
scale_fill_manual(values = c("#d8b365", "#f5f5f5"))
我的問題是我需要在圖中添加誤差線。 實現將與此類似。
geom_errorbar(aes(ymin=len-se, ymax=len+se), width=.1, position=pd)
然而,在數據被修改后,表 1 中包含的最大值和最小值信息將丟失。 我可以手動添加誤差線,但我有一些要繪制的圖,所以想知道是否有辦法通過管道保留這些信息。
非常感謝。
您可以使用dplyr
即時計算組件:
library(tidyverse)
df <- read_table(
"oligo condition score
REF Sample 27.827
REF Sample 24.622
REF Sample 31.042
REF Competitor 21.066
REF Competitor 18.413
REF Competitor 36.164
ALT Sample 75.465
ALT Sample 57.058
ALT Sample 66.408
ALT Competitor 35.420
ALT Competitor 17.652
ALT Competitor 21.466"
)
df %>%
group_by(oligo, condition) %>%
summarise(
mean = mean(score),
sd = sd(score),
n = n(),
se = sd / n
) %>%
ggplot(aes(x = oligo, y = mean, fill = condition)) +
geom_col(position = position_dodge()) +
geom_errorbar(
aes(ymin = mean - se, ymax = mean + se),
position = position_dodge2(padding = 0.5)
) +
labs(
title = "Mean Score ± 1 SE"
)
由reprex軟件包 (v0.2.1)創建於2019-04-01
您可以匯總多個值並保留min
max
和mean
:
emsa_test <- emsa_1 %>%
group_by(oligo,condition) %>%
summarise(mean=mean(score),min=min(score),max=max(score))
沒有足夠的聲譽來評論,但只是注意到 JasonAizkalns 的回答中的一個錯誤,以防其他人簡單地復制代碼:se = sd/sqrt(n)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.