ggplot2 - 按颜色分隔箱线图标签

ggplot2 - separating box plot labels by colour

我正在尝试为一些个人数据创建一个带有标签的箱线图。箱形图由两个变量分隔,映射到 x 和颜色。但是,当我使用 ggrepel 包中的 geom_text_repel 添加标签(真实数据所必需的)时,它们由 x 分隔但不是颜色。请参阅这个最小的可重现示例:

library(ggplot2)
library(ggrepel)

## create dummy data frame
rep_id <- c("a", "a", "b", "b", "c", "c", "d", "d", "e", "e")
dil <- c(1, 1, 1, 1, 2, 2, 2, 2, 2, 2)
bleach_time <- c(0, 24, 0, 24, 0, 24, 0, 24, 0, 24)
a_i <- c(0.1, 0.2, 0.35, 0.2, 0.01, 0.4, 0.23, 0.1, 0.2, 0.5)
iex <- data_frame(rep_id, dil, bleach_time, a_i)
rm(rep_id, dil, bleach_time, a_i)

## Plot bar chart of a_i separated by bleach_time and dil
p <- ggplot(iex, aes(x = as.character(bleach_time), y = a_i, fill = as.factor(dil))) +
geom_boxplot() +
geom_text_repel(aes(label = rep_id, colour = as.factor(dil)), na.rm = TRUE, segment.alpha = 0)

p

如您所见,标签采用颜色编码,但它们都围绕每对图的中心排列,而不是被图分开。我试过 nudge_x 但这会将所有标签移动到一起。有什么方法可以单独移动每组标签吗?

为了比较,这里是我的完整数据集的图,其中标有离群值 - 您可以看到每组标签如何不以其标记的点为中心,从而使解释复杂化:

看起来 geom_text_repel 需要 position = position_dodge(width = __),而不仅仅是我建议的 position = "dodge" shorthand,因此出现错误。您可以随意设置宽度; 0.7 对我来说还可以。

library(tidyverse)
library(ggrepel)

ggplot(iex, aes(x = as.character(bleach_time), y = a_i, fill = as.factor(dil))) +
  geom_boxplot() +
  geom_text_repel(aes(label = rep_id, colour = as.factor(dil)), na.rm = TRUE, 
    segment.alpha = 0, position = position_dodge(width = 0.7))

由于您正在绘制分布图,因此保持 y 轴上的位置相同可能很重要,并且只让 geom_text_repel 沿 x 轴抖动,所以我用 direction = "x", 这让我注意到了一些有趣的事情...

ggplot(iex, aes(x = as.character(bleach_time), y = a_i, fill = as.factor(dil))) +
  geom_boxplot() +
  geom_text_repel(aes(label = rep_id, colour = as.factor(dil)), na.rm = TRUE, 
    segment.alpha = 0, position = position_dodge(width = 0.7), direction = "x")

有一些文字被遮盖了,因为它们与箱线图的填充颜色相同!您可以使用颜色 + 填充调色板的更好组合来解决此问题。我做的快速修复是在 scale_*_discrete 调用中调低颜色的亮度并调高填充的亮度以使它们与众不同(但也很丑陋)。

ggplot(iex, aes(x = as.character(bleach_time), y = a_i, fill = as.factor(dil))) +
  geom_boxplot() +
  geom_text_repel(aes(label = rep_id, colour = as.factor(dil)), na.rm = TRUE, 
    segment.alpha = 0, position = position_dodge(width = 0.7), direction = "x") +
  scale_color_discrete(l = 30) +
  scale_fill_discrete(l = 100)

请注意,您还可以调整排斥中使用的力,因此如果您需要标签不重叠但也更靠近箱线图的中间,您也可以乱用该设置。