在 ggplot2 boxplots 顶部添加符号以指示变量的值

Add symbol on top of ggplot2 boxplots to indicate value of variable

使用更大数据集的以下子集,

ex <- structure(list(transect_id = c(1L, 1L, 1L, 1L, 1L, 15L, 15L, 
15L, 15L, 15L, 15L), number_f = c(2L, 2L, 2L, 2L, 2L, 0L, 0L, 
0L, 0L, 0L, 0L), years_f = c(1L, 1L, 1L, 1L, 1L, 6L, 6L, 6L, 
6L, 6L, 6L), b = c(5.036625862, 6.468666553, 8.028989792, 4.168409348, 
5.790089607, 10.67796993, 9.371051788, 10.54364777, 6.904324532, 
7.203606129, 9.1611166)), .Names = c("transect_id", "number_f", 
"years_f", "b"), class = "data.frame", row.names = c(1L, 2L, 
3L, 4L, 5L, 2045L, 2046L, 2047L, 2048L, 2049L, 2050L))

我已经为 "transect_id" 指示的每个组绘制了 "b" 的分布,并用 "number_f" 对它们进行了着色,我在这里这样做:

ggplot(aes(x=reorder(transect_id, b, FUN=median), y=b), data=ex) + geom_boxplot(aes(fill=as.factor(number_f))) + xlab('Transect ID')

我需要为每个 "transect_id" 组做的是堆栈符号 - 星号或其他一些符号 - 在每个箱线图的顶部提供 [= 值的指示32=] 对应于每个 "transect_id"。在下面的数据子集中,对于 transect_ids 1 和 15,"years_f" 分别等于 1 和 6。我想看到这样的东西,这是我手动模拟的。

另外请记住,我正在使用的数据集非常大,因此我需要使用一些循环或其他一些自动执行此操作的方法。请注意,我绝对欢迎其他想法以更好的方式指示 "years_f" 的值,这可能不会像拥有所有这些堆叠的符号那样使数字负担过重,这对于更大的 [=32= 值尤其是一个问题].

尝试添加

annotate('text', x = c(1, 2), y = 3, label =  paste0('Year_F =', unique(ex$years_f)))

像这样到你的情节的结尾:

ggplot(aes(x=reorder(transect_id, b, FUN=median), y=b), data=ex) + 
    geom_boxplot(aes(fill=as.factor(number_f))) + xlab('Transect ID')+ 
    annotate('text', x = c(1, 2), y = 3, label =  paste0('Year_F =', unique(ex$years_f)))

要在更大的数据集上使用它,您必须编辑 xy 参数,但这可能是一个不错的选择。 y 坐标的可能性可能类似于 0.9 * min(ex$b).

编辑 回复您的评论:

你可以先数一下transect_id有多少层来指定x

len.levels <- length(levels(as.factor(ex$transect_id)))

然后,您可以通过 transect_id:

创建 uniqe years_f 变量的摘要 table
sum.table <- aggregate(years_f~reorder(ex$transect_id, ex$b, median),
                       data = ex, FUN = unique)

  reorder(ex$transect_id, ex$b, median) years_f
1                                     1       1
2                                    15       6

然后绘制如下:

ggplot(aes(x=reorder(transect_id, b, FUN=median), y=b), data=ex) + 
  geom_boxplot(aes(fill=as.factor(number_f))) + xlab('Transect ID')+ 
  annotate('text', x = 1:len.levels, y = .9 * min(ex$b), 
           label =  paste0('Year_F =', sum.table[,2]))