我試圖顯示組之間的百分比變化。作為基本方法,我想將所有組的平均值與默認值進行比較,并僅以 [%] 顯示這些差異。但是,我希望以某種方式表示均值內的可變性,比如說標準偏差。但是,我不確定如何展示這一點,實際上是否有意義?
這是我的平均值和誤差線的簡單條形圖示例,計算為mean和sd:
dd <- data.frame(id = rep(c(1,2,3), 2),
vol = c(10,5,8,11,10,9),
reg = rep(c('control', 'new'), each = 3))
# calculate mean and sd
sum_dd <- dd %>%
group_by(reg) %>%
summarize(V_mean = mean(vol, na.rm = T),
V_sd = sd(vol, na.rm = T)) #
# Plot bar plot and error bars
sum_dd %>%
ggplot(aes(x = reg,
y = V_mean))
geom_bar(stat = 'identity')
geom_errorbar(aes(x=reg,
min=V_mean-V_sd,
ymax=V_mean V_sd)) #
此繪圖生成帶有誤差線的漂亮條形圖,很明顯我means和sd每個組是什么:

但是,如何表示該組new從 % 變化control?
在這里,我需要先計算從control到的 % 變化new。然后我可以繪制百分比變化的條形圖。但是我可以從哪些值計算標準偏差之類的東西來繪制并顯示我的結果中的可變性(使用例如誤差線)?
sum_dd %>%
group_by(reg) %>%
# Calculate % change from a to b value
mutate(control_mean = 7.67,
perc_change = (10-7.67)/7.67 * 100) %>%
filter(reg !='control') %>%
ggplot(aes(x = reg,
y = perc_change))
geom_bar(stat = 'identity') #
# from which values calculate the error bar??
geom_errorbar(aes(x=reg,
min=V_mean-V_sd,
ymax=V_mean V_sd)) #
謝謝你的想法!
uj5u.com熱心網友回復:
首先,您可以stat_summary()更輕松地使用原始繪圖,因為它會直接在呼叫中為您計算mean和。SDggplot()
ggplot()但是對于您的問題,您可以通過mutate()設定vol[reg == "control"]為分母的位置輕松計算在傳遞到之前的倍數變化。y然后您可以使用 {scales}格式化軸。
library(tidyverse)
library(scales)
dd <- data.frame(id = rep(c(1,2,3), 2),
vol = c(10,5,8,11,10,9),
reg = rep(c('control', 'new'), each = 3))
# original plot using stat_summary to avoid transforming data
dd %>%
ggplot(aes(reg, vol))
stat_summary(geom = "bar", fun = mean)
stat_summary(geom = "errorbar", fun.data = mean_cl_normal, fun.args = list(mult = 1))

# calculate % of control
dd %>%
mutate(norm_vol = vol/mean(vol[reg == "control"])) %>%
ggplot(aes(reg, norm_vol))
stat_summary(geom = "bar", fun = mean)
stat_summary(geom = "errorbar", fun.data = mean_cl_normal, fun.args = list(mult = 1))
scale_y_continuous(labels = scales::percent_format())

由reprex 包于 2022-02-21 創建(v2.0.1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/430660.html
上一篇:虛擬分類變數的條形圖
下一篇:將更多資料添加到其他df的熱圖中
