向 geom_boxplot 添加紧凑的字母显示

问题描述 投票:0回答:1

我想将紧凑的字母显示结果添加到

geom_boxplot
。 CLD 是根据事后 Dunn 测试生成的。我想在胡须上方添加字母,就像在 geom_bar 上添加错误栏一样(例如,

`geom_errorbar(aes(ymin = mean_result - se_result, ymax = mean_result + se_result, 
position = position_dodge(.9), width=.1, linewidth = .5, col = 'black')`). 

我查看了这个,但它不适用于我的数据集。

这是一些虚拟代码

 # SOME DUMMY DATA
 
df <- data.frame (Treatment = as.factor(rep (c('A', 'B', 'C', 'D'), each = 48)), result 
= rnorm(192, mean = c(0.8, 0.3, 0.65, 1), sd = c(0.02, 0.07, 0.9, 0.3)))
 
 # PERFORM POST-HOC
 kw_test <-dunnTest(result ~ Treatment , data = df, method="bonferroni",kw=TRUE)$res
 
 
 # ASSIGN LETTERS
 kw_let<- cldList(P.adj ~ Comparison, data = kw_test,threshold  = 0.05)
 letters <- data.frame(Treatment = unique(df$Treatment), Letter = kw_let[2])



 p <- ggplot(df, aes(x = Treatment, y = result ))+
  geom_boxplot()+
  geom_jitter()+
  coord_cartesian(ylim = c(-1,3))

这就是我陷入困境的地方。我需要计算出每个盒子的晶须高度,然后将 CLD 结果添加到每个盒子上方,与晶须顶部上方的距离相同。下面的代码本应计算出每个盒子的胡须高度,但结果是一样的。当我尝试添加

geom_text

时,我也收到错误
top_whiskers  <- data.frame(df %>%
                          group_by(Treatment) %>%
                          summarise(top_whisker = quantile(df$result, 0.75) + 1.5 * 

IQR(df$result)))

letters$whisker <- top_whiskers


p +  geom_text(data=kw_let, aes(x=Treatment, y = whisker.top_whisker , label = 
Letter),vjust= -.5)

非常感谢任何帮助

r ggplot2 boxplot
1个回答
0
投票

一种选择是使用

boxplot.stats
来获取晶须的极值:

library(ggplot2)

names(kw_let)[1] <- "Treatment"

letters <- kw_let |>
  merge(
    aggregate(
      result ~ Treatment,
      data = df, FUN = \(x) boxplot.stats(x)$stats[5]
    )
  )

ggplot(df, aes(x = Treatment, y = result)) +
  geom_boxplot() +
  geom_jitter() +
  geom_text(
    data = letters,
    aes(label = Letter),
    vjust = 0,
    nudge_y = .1,
    color = "red"
  ) +
  coord_cartesian(ylim = c(-1, 3))

或使用

dplyr
:

letters <- kw_let |>
  dplyr::left_join(
    dplyr::summarise(
      df,
      result = boxplot.stats(result)$stats[5], .by = Treatment
    )
  )

数据

# SOME DUMMY DATA
set.seed(123)

df <- data.frame(
  Treatment = as.factor(rep(c("A", "B", "C", "D"), each = 48)),
  result = rnorm(192, mean = c(0.8, 0.3, 0.65, 1), sd = c(0.02, 0.07, 0.9, 0.3))
)

# PERFORM POST-HOC
kw_test <- FSA::dunnTest(result ~ Treatment,
  data = df,
  method = "bonferroni", kw = TRUE
)$res

# ASSIGN LETTERS
kw_let <- rcompanion::cldList(P.adj ~ Comparison,
  data = kw_test, threshold = 0.05
)
© www.soinside.com 2019 - 2024. All rights reserved.