ggplot2在boxplots上添加文本

时间:2014-04-15 23:03:52

标签: r ggplot2 label boxplot

我有一个数据,我在ggplot2上绘制的箱形图看起来像

> head(varf)
             sID variable       value
1 SP_SA036,SA040   CM0001 0.492537313
2 SP_SA036,SA040   CM0001 0.479564033
3 SP_SA036,SA040   CM0001 0.559139785
4 SP_SA036,SA040   CM0001 0.526806527
5 SP_SA036,SA040   CM0001 0.009049774
6 SP_SA036,SA040   CM0001 0.451612903

变量列包含16个不同的ID(从CM0001到CM0016)

我有一个带注释的数据框

category   annotation
CM001      HG4450
CM002      HG3288
..
CM016      MM8998

我想将这些注释映射到我的箱图上,但是找不到办法,将geom_text与boxplot一起使用的正确语法是什么?

由于

2 个答案:

答案 0 :(得分:5)

有很多方法可以解决这个问题,例如: herehere。可能最简单的方法是

meds <- c(by(mtcars$mpg, mtcars$cyl, median))
ggplot(mtcars, aes(factor(cyl), mpg)) +
    geom_boxplot() + 
    geom_text(data=data.frame(), aes(x=names(meds), y=meds, label=1:3), col='red', size=10)

enter image description here

答案 1 :(得分:3)

varf <- read.table(text = "sID variable       value
SP_SA036,SA040   CM0001 0.492537313
SP_SA036,SA040   CM0001 0.479564033
SP_SA036,SA040   CM0001 0.559139785
SP_SA036,SA040   CM0002 0.526806527
SP_SA036,SA040   CM0002 0.009049774
SP_SA036,SA040   CM0002 0.451612903", header = T)

anot <- read.table(text = "category   annotation
CM0001      HG4450
CM0002      HG3288", header = T)

varf <- merge(varf, anot, by.x = "variable", by.y = "category", all.x = T)

library(data.table)
quants <- data.table(varf)[, list(quant = as.numeric(quantile(value)[3])), by = variable]
ggplot(varf, aes(x = variable, y = value, fill = variable)) + 
  geom_boxplot() +
  geom_text(data = quants, aes(x = variable, y = quant, label = variable), size = 10)

enter image description here

相关问题