我一直在使用 ggplot2 創建一個簡單的分組箱線圖:
ggplot(data=all_data, aes(x=Season,y=`Depth (m)`,fill=site))
geom_boxplot()
xlab(NULL)
這使得這

但有幾件事我想編輯。首先是盒子的順序,我想在左邊保持“干”,在右邊保持“濕”,但我想顛倒站點順序,使“上游”在左邊,“下游”在每個組內的權利。另外,我嘗試在平均值上添加誤差線寬度和形狀,但是當我使用類似的東西時:
ggplot(data=all_data, aes(x=Season,y=`Depth (m)`,fill=site))
geom_boxplot()
stat_boxplot(geom = 'errorbar',width=0.1)
stat_summary(fun=mean, geom="point",shape=88,size=3)
xlab(NULL)
它產生這個

我將不勝感激編輯此內容的任何幫助。
uj5u.com熱心網友回復:
要重新排列上游/下游類別,請轉換site為具有適當級別的因子。為了讓您的誤差線和點與您的箱線圖對齊,您需要確保將它們包含position = position_dodge(width = 0.75)在它們的圖層中,否則它們將落在箱線圖之間。
所以你的代碼看起來像這樣:
ggplot(data=all_data, aes(x = Season, y = `Depth (m)`,
fill = factor(site, c('Upstream', 'Downstream'))))
geom_boxplot()
stat_boxplot(geom = 'errorbar', width = 0.1,
position = position_dodge(width = 0.75))
stat_summary(fun = mean, geom = "point", shape = 88, size = 3,
position = position_dodge(width = 0.75))
labs(x = NULL, fill = 'Site')

使用的資料
OP 沒有提供資料,因此我使用以下代碼制作了具有相似特征的資料集:
set.seed(1)
all_data <- data.frame(Season = rep(c('Dry', 'Wet'), each = 200),
`Depth (m)` = c(rnorm(100, 1.5, 0.5),
rnorm(100, 1.75, 0.25),
rnorm(100, 1.6, 0.3),
rnorm(100, 1.9, 0.5)),
site = rep(rep(c('Downstream', 'Upstream'), 2), each = 100),
check.names = FALSE)
在此資料上運行 OP 的繪圖代碼會產生:
ggplot(data = all_data, aes(x=Season,y=`Depth (m)`,fill=site))
geom_boxplot()
xlab(NULL)

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/451543.html
上一篇:根據R中另一列的條件繪制圖表
