如何用ggplot2标记boxplot的离群值?

时间:2018-07-31 07:19:25

标签: r ggplot2 label

我的数据如下:

genes   fc   type
349028  -1.2 pro
2454    1.1  pro
24908   0.4  pro
4730    0.8  pro
94988   0.9  pro
9865    6    pro
8935    3.4  phos
39280   1.2  phos
8034    -0.3 phos
3953    1.1  phos
4732    2.1  phos

我想用ggplot2标记boxplot的异常值,并用“抖动”绘制所有点,但是异常值出现两次。我的代码如下:

pathdata=read.table(file="data.txt",header=TRUE,quote="",sep="\t")
library(ggplot2)
library(dplyr)
is_outlier <- function(x) {
  return(x < quantile(x, 0.25) - 1.5 * IQR(x) | x > quantile(x, 0.75) + 1.5 * IQR(x))
}
pathdata %>%
	group_by(type) %>%
	mutate(outlier=ifelse(is_outlier(fc),genes,as.numeric(NA))) %>%
	ggplot(., aes(x = factor(type), y = fc)) +
    geom_boxplot() + 
	geom_point(size=1.5, aes(x=jitter(as.numeric(type)), color = fc))+
	scale_colour_gradient(low="blue",high="red") +
    geom_text(aes(label = outlier), na.rm = TRUE, hjust = -0.3)

我明白了:enter image description here

如果我在outlier.size=-1中添加geom_boxplot(),则会得到: enter image description here

但是标签距离代表点不近。有人可以告诉我如何调整我的代码吗?谢谢!

2 个答案:

答案 0 :(得分:4)

您可以尝试将ggbeeswarm用作点,将ggrepel用作漂亮的标签。 值得注意的是,使用outlier.colour = NA从箱线图中删除离群值,并在geom_text_repel

中将数据子集化
d %>% 
  group_by(type) %>%
  mutate(outlier=ifelse(is_outlier(fc),genes,as.numeric(NA))) %>%
  ggplot(aes(x=factor(type), fc)) + 
    geom_boxplot(outlier.colour = NA) +
    ggbeeswarm::geom_beeswarm(aes(color=fc)) +
    ggrepel::geom_text_repel(data=. %>% filter(!is.na(outlier)), aes(label=genes)) +
    scale_colour_gradient(low="blue",high="red")

enter image description here

答案 1 :(得分:0)

可能会重复adding text to ggplot geom_jitter points that match a condition

您只需将抖动值与标签一起存储在单独的数据框中,并在geom_pointgeom_text内使用此数据框即可保持一致性。