在ggplot2的箱线图中标记箱子

5
我希望在由ggplot2生成的箱线图中,每个框上方都有一个标签显示。
例如:
#Example data
test = c("A", "A", "A", "A", "A", "A", "B", "B", "B", "B", "B", "B")
patient = c(1, 1, 2, 2, 3, 3, 1, 1, 2, 2, 3, 3)
result =  c(5, 7, 2 ,4, 6, 7, 3, 5, 5, 6, 2 ,3)
data <- tibble(test, patient, result)

#Labels I want to include
Alabs = c(1, 3, 500)
Blabs = c(8, 16, -32)

#Plot data
ggplot(data, aes(x = factor(patient), y = result, color = factor(test))) + 
  geom_boxplot(outlier.shape = 1)

给出情节:

enter image description here

我想要打印出第一个病人的 Alabs 的第一个元素在红色框上方,第二个病人的 Alabs 的第二个元素在红色框上方,第一个病人的 Blabs 的第一个元素在蓝色框上方,以此类推。

我该如何实现?

2个回答

4
我会创建一个单独的标签数据集来添加这些标签。
labs = tibble(test = rep(LETTERS[1:2], each = 3),
                  patient = c(1, 2, 3, 1, 2, 3),
                  labels = c(1, 3, 500, 8, 16, -32) )

   test patient labels
  <chr>   <dbl>  <dbl>
1     A       1      1
2     A       2      3
3     A       3    500
4     B       1      8
5     B       2     16
6     B       3    -32

上述内容包含了有关x轴和分面变量的所有信息,但缺少有关y轴文本位置的信息。为了将这些文本放在框上方,我们可以计算每个因子组合的最大值加上一个小的y位置值(虽然geom_text有一个有用的nudge_y参数,但它在躲闪时不起作用)。
我通过dplyr按组生成摘要,然后将y位置值与标签数据集连接起来。
library(dplyr)

labeldat = data %>%
     group_by(test, patient) %>%
     summarize(ypos = max(result) + .25 ) %>%
     inner_join(., labs)

现在,您可以添加geom_text层,使用标签数据集。为了避免与箱线图相同的方式闪避这些内容,使用position_dodge。为了防止字母出现在图例中,我使用show.legend = FALSE

ggplot(data, aes(x = factor(patient), y = result, color = test)) + 
     geom_boxplot(outlier.shape = 1) +
     geom_text(data = labeldat, aes(label = labels, y = ypos), 
               position = position_dodge(width = .75), 
               show.legend = FALSE )

enter image description here


1
需要一些欺骗手段才能将标签放入同一个tibble中:
data$labs=c(NA, 1, NA, 3, NA, 500, NA, 8, NA, 16, NA, -32) #line up the labels so each patient gets one: if you put the NAs first, labels will be at the bottom of the boxes
data$lab_x=c(NA, 0.75, NA, 1.75, NA, 2.75, NA, 1.25, NA, 2.25, NA, 3.25) #set x position for each one

然后运行ggplot:
 ggplot(data, aes(x = factor(patient), y = result, color = factor(test))) + 
   geom_boxplot(outlier.shape = 1)+
   geom_text(aes(label=labs, x=lab_x))

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接