其他
R语言绘制蝴蝶(柱状)图示例
今天再介绍一种柱状图,蝴蝶图。因形似蝴蝶,故俗称蝴蝶图。事实上昨天介绍过的“双向柱状图”就是蝴蝶图的一种类型,毕竟两侧对称嘛。在蝴蝶图中,两侧数据即可共享同一坐标轴,也可各自独立。先前的ggplot2绘制双向柱状图中,我们的数据共用同一坐标轴;因此本文再展示ggplot2绘制分开坐标轴的情形。
鉴于白鱼小编的一贯作风,实在懒得自己想,就仿别人的来。例如这篇文献中使用了“蝴蝶图”的柱状图样式,展示了top10 GO和KEGG富集通路(“LncRNA Expression Profile of Human Thoracic Aortic Dissection by High- Throughput Sequencing”)。正好图中两侧坐标轴各自独立的,那么今天咱们就准备整个类似的出来。
ggplot2绘制蝴蝶图
up <- read.delim('GO.MF.up.txt', sep = '\t', stringsAsFactors = FALSE)
down <- read.delim('GO.MF.down.txt', sep = '\t', stringsAsFactors = FALSE)
#按 p 值排序,同时当两数据不等长时补充空白数据(尽可能使蝴蝶图对称)
up <- up[order(up$P_Value, decreasing = TRUE), ]
up$Term <- factor(up$Term, levels = up$Term)
id_up <- levels(up$Term)
down <- down[order(down$P_Value, decreasing = TRUE), ]
down$Term <- factor(down$Term, levels = down$Term)
id_down <- levels(down$Term)
n <- length(up$Term) - length(down$Term)
if (n > 0) {
down$Term <- as.character(down$Term)
for (i in paste('nn', as.character(seq(1, n, 1)), sep = '')) down <- rbind(list(i, NA, NA), down)
down$Term <- factor(down$Term, levels = down$Term)
id_down <- c(rep('', n), id_down)
} else if (n < 0) {
up$Term <- as.character(up$Term)
for (i in paste('nn', as.character(seq(1, abs(n), 1)), sep = '')) up <- rbind(list(i, NA, NA), up)
up$Term <- factor(up$Term, levels = up$Term)
id_up <- c(rep('', abs(n)), id_up)
}
library(ggplot2)
#上调 GO
p_up <- ggplot(up, aes(Term, log(P_Value, 10))) +
geom_col(fill = 'red2', color = 'black', width = 0.6) +
theme(panel.grid = element_blank(), panel.background = element_rect(fill = 'transparent')) +
theme(axis.line.x = element_line(colour = 'black'), axis.line.y = element_line(colour = 'transparent'), axis.ticks.y = element_line(colour = 'transparent')) +
theme(plot.title = element_text(hjust = 0.5, face = 'plain')) +
coord_flip() +
geom_hline(yintercept = 0) +
labs(x = '', y = '', title = 'UP') +
scale_y_continuous(expand = c(0, 0), breaks = c(-12, -8, -4, 0), labels = as.character(abs(c(-12, -8, -4, 0)))) + #这儿更改间距设置
scale_x_discrete(labels = id_up)
#下调 GO
p_down <- ggplot(down, aes(Term, -log(P_Value, 10))) +
geom_col(fill = 'green4', color = 'black', width = 0.6) +
theme(panel.grid = element_blank(), panel.background = element_rect(fill = 'transparent')) +
theme(axis.line.x = element_line(colour = 'black'), axis.line.y = element_line(colour = 'transparent'), axis.ticks.y = element_line(colour = 'transparent')) +
theme(plot.title = element_text(hjust = 0.5, face = 'plain')) +
geom_hline(yintercept = 0) +
coord_flip() +
labs(x = '', y = '', title = 'DOWN') +
scale_y_continuous(expand = c(0, 0), breaks = c(0, 2, 4, 6), labels = as.character(c(0, 2, 4, 6))) + #这儿更改间距设置
scale_x_discrete(labels = id_down, position = 'top')
library(cowplot)
pdf('butterfly.pdf', width = 14, height = 5)
plot_grid(p_up, p_down, nrow = 2, ncol = 2, rel_heights = c(9, 1), labels = 'GO_Enrichment Score (-log10(p-value))', label_x = 0.5, label_y = 0, label_fontface = 'plain')
dev.off()
正如开篇提到的,对于两侧共享坐标轴的蝴蝶图,参考前文“双向柱状图”即可。
友情链接