2

我正在尝试为一些个人数据创建一个带有标签的箱线图。箱线图由两个变量分隔,映射到 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 但这会将所有标签一起移动。有没有办法可以单独移动每组标签?

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

在此处输入图像描述

4

1 回答 1

1

它看起来像geom_text_repel需要position = position_dodge(width = __),而不仅仅是position = "dodge"我建议的速记,因此是错误。你可以乱设置宽度;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)

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

于 2018-05-31T14:20:36.743 回答