ggplot2|玩转Manhattan图-你有被要求这么画吗?

2023-06-05,,

本文首发于“生信补给站”,ggplot2|玩转Manhattan图-你有被要求这么画吗?更多关于R语言,ggplot2绘图,生信分析的内容,敬请关注小号。

Manhattan图算是GWAS分析的标配图了,可参考Bio|manhattan图 进行绘制。

由于Manhattan点太多,后期AI/PS修改的话难度有点大,如果可以“个性化”绘制的话那是极好的!

一 载入R包,数据

1)载入数据处理的tidyverse包,使用qqman中gwasResults示例数据集

#载入R包
#install.packages("qqman")
library(qqman)
library(tidyverse)
#查看原始数据
head(gwasResults)
SNP CHR BP         P
1 rs1   1  1 0.9148060
2 rs2   1  2 0.9370754
3 rs3   1  3 0.2861395
4 rs4   1  4 0.8304476
5 rs5   1  5 0.6417455
6 rs6   1  6 0.5190959

我们知道Manhattan图实际就是点图,横坐标是chr,纵坐标是-log(Pvalue) ,原始P值越小,-log转化后的值越大,在图中就越高。

原始数据中重要的“元素”都有了 ,我们自己的数据也是只需要这四列就可以了。注意绘制前需要转化一下:

2)处理原始数据---计算SNP的累计位置

# 1)计算chr长度
chr_len <- gwasResults %>%
 group_by(CHR) %>%
 summarise(chr_len=max(BP))

# 2) 计算每条chr的初始位置
chr_pos <- chr_len  %>%
 mutate(total = cumsum(chr_len) - chr_len) %>%
 select(-chr_len)

#3)计算累计SNP的位置
Snp_pos <- chr_pos %>%
 left_join(gwasResults, ., by="CHR") %>%
 arrange(CHR, BP) %>%
 mutate( BPcum = BP + total)

#查看转化后的数据
head(Snp_pos,2)

 SNP CHR BP         P total BPcum
1 rs1   1  1 0.9148060     0     1
2 rs2   1  2 0.9370754     0     2

数据准备完成,开始绘图。

二 ggplot2绘制Manhattan图

1 纵坐标为P值转-log10()

ggplot(Snp_pos, aes(x=BPcum, y=-log10(P))) +
geom_point( aes(color=as.factor(CHR)))

基本图形出来了,但是有点怪;不急,一点点改进:

横坐标标签设置在每个chr中间位置;

背景色去掉,线去掉等

去掉点和X轴之间的 “gap” (很多地方可用)

添加阈值线

2 绘制加强版Manhattan图

1) 准备X轴标签位置--在每条chr的中间

X_axis <-  Snp_pos %>% group_by(CHR) %>% summarize(center=( max(BPcum) + min(BPcum) ) / 2 )

2)绘制“改良版”Manhattan图

p <- ggplot(Snp_pos, aes(x=BPcum, y=-log10(P))) +
#设置点的大小,透明度
  geom_point( aes(color=as.factor(CHR)), alpha=0.8, size=1.3) +
#设置颜色
  scale_color_manual(values = rep(c("grey", "skyblue"), 22 )) +
#设定X轴
  scale_x_continuous( label = X_axis$CHR, breaks= X_axis$center ) +
#去除绘图区和X轴之间的gap
  scale_y_continuous(expand = c(0, 0) ) +  
#添加阈值线
geom_hline(yintercept = c(6, -log10(0.05/nrow(Snp_pos))), color = c('green', 'red'), size = 1.2, linetype = c("dotted", "twodash")) +
#设置主题
  theme_bw() +
  theme(
    legend.position="none",
    panel.border = element_blank(),
    axis.line.y = element_line(),
 panel.grid.major.x = element_blank(),
 panel.grid.minor.x = element_blank()
)

这时候是不是就可以了,

ggplot2|玩转Manhattan图-你有被要求这么画吗?的相关教程结束。

《ggplot2|玩转Manhattan图-你有被要求这么画吗?.doc》

下载本文的Word格式文档,以方便收藏与打印。