在 ggplot2 中,我使用該stat_summary()函式來計算和繪制資料集的均值和標準差。我同時使用facet_wrap()將資料集分成兩個圖。令我驚喜的是,添加facet_wrap()到我的 ggplot 導致stat_summary()正確地獨立應用于每個資料子集。
df>
| ID | Group | Strain | Condition | DoublingTime |
|-----------|-------|--------|-----------|-----------------|
| A_3g_Rep1 | A_3g | A | 3g | 122.4135 |
| A_3g_Rep2 | A_3g | A | 3g | 124.5801 |
| A_3g_Rep3 | A_3g | A | 3g | 124.9419 |
| A_6g_Rep1 | A_6g | A | 6g | 120.5004 |
| A_6g_Rep2 | A_6g | A | 6g | 124.1666 |
| A_6g_Rep3 | A_6g | A | 6g | 124.6453 |
| B_3g_Rep1 | B_3g | B | 3g | 132.568 |
| B_3g_Rep2 | B_3g | B | 3g | 137.5242 |
| B_3g_Rep3 | B_3g | B | 3g | 135.5238 |
| B_6g_Rep1 | B_6g | B | 6g | 137.1333 |
| B_6g_Rep2 | B_6g | B | 6g | 142.733 |
| B_6g_Rep3 | B_6g | B | 6g | 140.0722 |
首先,我使用了以下正確計算平均值和標準偏差值的方法。但是,它包括 x 軸上的組,這些組不存在于構面中。
DT_plotA <- ggplot(df, aes(Group, DoublingTime))
stat_summary(fun.data="mean_sdl", fun.args = list(mult=1),
geom="errorbar", width=0.5)
stat_summary(fun=mean, geom="point", size=3)
facet_wrap(nrow = 1, .~Strain)
令我驚喜的是,將我的 aes() x 值調整為 Condition 同時包含 facet_wrap() 導致 stat_summary() 正確計算每個組的平均值和標準差。
DT_plotB <- ggplot(df, aes(Condition, DoublingTime))
stat_summary(fun.data="mean_sdl", fun.args = list(mult=1),
geom="errorbar", width=0.5)
stat_summary(fun=mean, geom="point", size=3)
facet_wrap(nrow = 1, .~Strain)
但是,如果從圖中洗掉了 facet_wrap,則 stat_summary 會根據 Condition 計算平均值和標準差:對來自獨立菌株的資料進行平均。我擔心這個警告會被遺忘,并導致在移除 facet 時不正確計算均值/標準差。
DT_plotC <- ggplot(df, aes(Condition, DoublingTime))
stat_summary(fun.data="mean_sdl", fun.args = list(mult=1),
geom="errorbar", width=0.5)
stat_summary(fun=mean, geom="point", size=3)
問題
有沒有辦法生成一個看起來像 DT_plotB 但包含 aes(Group, DoublingTime) 的繪圖,如 DT_plotA 的代碼所示?
uj5u.com熱心網友回復:
也許我們可以對資料進行一些預處理 -> 計算平均值和標準差:
library(dplyr)
library(ggplot2)
df %>%
group_by(Strain, Condition) %>%
mutate(mean = mean(DoublingTime),
sd = sd(DoublingTime)) %>%
ggplot(aes(x = Condition, y=mean))
geom_point()
geom_errorbar(aes(ymin = mean-sd, ymax = mean sd), width=.2)
facet_wrap(.~Strain)

轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/529891.html
標籤:rggplot2刻面
上一篇:有沒有一種快速的方法可以將間隔(開始和結束)轉換為R中此間隔中的數字串列
下一篇:gt()表-標題顏色
