【问题标题】:ggplot2 - separating box plot labels by colourggplot2 - 按颜色分隔箱线图标签
【发布时间】:2018-05-31 12:09:42
【问题描述】:

我正在尝试为一些个人数据创建一个带有标签的箱线图。箱线图由两个变量分隔,映射到 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 中分配了aes 之外的颜色;它需要进入内部才能映射到美学
  • 您在该行中还缺少一个逗号
  • 感谢您发现错误@camille - 我现在已经修正了。
  • 酷,现在尝试给文本一个position = "dodge"。箱线图会自动躲开——如果不这样做,它们只会相互重叠——但文本不一定
  • 这引发了一个错误,但我设法让它与position = position_dodge(width = 0.9) 一起工作。感谢您的帮助!如果您想提交该答案作为答案,我可以接受并给您声誉。

标签: r ggplot2 ggrepel


【解决方案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)

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-01
    • 1970-01-01
    • 2016-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多