ggplot - 为从预先计算的值创建的箱形图添加标签

时间:2018-02-10 14:01:25

标签: r ggplot2 boxplot

给出如下所示的数据框df

df <- data.frame(x=c("A","B"), min=c(1,2), low=c(2,3), mid=c(3,4), top=c(4,5), max=c(5,6))

使用ggplot,可以创建如下图所示的框图

library(ggplot2)

ggplot(df, aes(x=x, ymin = min, lower = low, middle = mid, upper = top, ymax = max)) +
  geom_boxplot(stat = "identity")

enter image description here

我需要在箱子图中添加五个点的标签(就在每个盒子右侧的方框外面) - 我该如何解决这个问题?

注意 - 这是关于从预先计算的箱线图点数据中获取与问题here不同的标签

更新

www提供的答案适用于原始数据集。但是,当我尝试使用不同但相似的数据集时,会出错。

text <- "
test,group,varType,X25th,X50th,X5th,X75th,X95th
Test1,A,varC,20,25,2.0,35,65
Test1,A,varD,2,3,0.2,5,9
Test1,B,varC,30,35,3.0,45,75
Test1,B,varD,8,9,0.8,11,15
"
plotDat <- read.table(textConnection(text), sep=",", header = T, stringsAsFactors = F)

# for labels
plotLabels <- plotDat %>% gather(Col, Val, -c(test, group, varType))

ggplot(plotDat, 
       aes(x = group, ymin = X5th, lower = X25th,
           middle = X50th, upper = X75th, ymax = X95th,
           fill=group)) +
  geom_boxplot(stat = "identity") +
  geom_errorbar() +
  facet_wrap( ~ varType, scale = "free_y")  + 
  geom_text(data = plotLabels, aes(x = group, y = Val, label = Val),
            nudge_x = 0.1, nudge_y = 0.3) 

我得到的错误是Error in eval(expr, envir, enclos) : object 'X5th' not found

1 个答案:

答案 0 :(得分:3)

我们可以将df转换为长格式,然后使用geom_text绘制它。

library(tidyr)

df2 <- df %>% gather(Col, Val, -x)

ggplot(df) +
  geom_boxplot(stat = "identity", 
               aes(x=x, ymin = min, lower = low, middle = mid, upper = top, ymax = max)) + 
  geom_text(data = df2, aes(x = x, y = Val, label = Col), nudge_x = 0.1, nudge_y = 0.3)

enter image description here

我们也可以使用geom_label

ggplot(df) +
  geom_boxplot(stat = "identity", 
               aes(x=x, ymin = min, lower = low, middle = mid, upper = top, ymax = max)) + 
  geom_label(data = df2, aes(x = x, y = Val, label = Col), nudge_x = 0.1, nudge_y = 0.3)

enter image description here

不确定是否要添加统计信息文本(minlow ...)或实际数字(23,... ),但对于后一种情况,只需将label = Val设置为

即可