学习来源
生信技能树课程以及sthda学习网站http://www.sthda.com/english/wiki/ggplot2-essentials。在此表示感谢
代码如下
library(dplyr)#用管道符和filter()函数
library(tidyr)#用drop_na()函数或replace_na()函数
dat = deg
logFC_cutoff = 0.5
dat$change = as.factor(
ifelse(deg$P.Value<0.05&abs(deg$logFC)>logFC_cutoff,
ifelse(deg$logFC>logFC_cutoff,
"up","down"),
"not")
)
table(dat$change)
for_label_up = dat[gene_label$up,]%>%drop_na()%>%filter(change=="up")#data.frame文件
for_label_down = dat[gene_label$down,]%>%drop_na()%>%filter(change=="down")#data.fame文件
for_label1 = rbind(for_label_down, for_label_up)
for_label_tup <- dat%>% filter(change=="up") %>%head(5)
for_label_tdown <- dat%>% filter(change=="down") %>%head(5)
#正则表达式
library(stringr)#使用str_detect()函数
for_label_tdown <- for_label_tdown[!str_detect(rownames(for_label_tdown),'^(gene1_name|gene2_name)'),]
for_label_t = rbind(for_label_tdown,for_label_tup)
#火山图作图
library(ggplot2)
p <- ggplot(data = dat, aes(x=logFC, y=-log10(P.Value)))+
geom_point(alpha = 0.5, size=2, aes(color=change))+#点映射
ggtitle("title")+#添加图标题
ylab("-log10(pvalue)")+#标记y轴标题
scale_color_manual(values = c("green","grey","red"),name="groups", labels = c("down(??)","stable(??)", "up(??)"))+#标记点颜色,标记图例信息 #改变图例颜色(RGB配色)c("#01BA38","#619CFF","#F8766D")
geom_vline(xintercept = c(-logFC_t,logFC_t), lty = 4, col = "black", lwd=0.8)+#添加水平线
geom_text(aes(-logFC_t, 0, label = "logFC = -0.5"), size = 4)+#添加水平线标记
geom_text(aes(logFC_t, 0, label = "logFC = 0.5"), size = 4)+#添加水平线标记
geom_hline(yintercept = -log10(0.05),lty=4, col="black", lwd=0.8)+#添加垂直线
geom_text(aes( -3.5, -log10(0.05), label = "-log10(0.05)", vjust=-1), size = 4)+#添加垂直线标记
scale_y_continuous(breaks=c(round(-log10(0.05),1),50, 100, 150), labels = c("1.3", "50", "100", "150"))+#改变Y轴标签,计量型资料/连续性资料
theme_bw()+
theme(legend.title = element_text(size = 15, face = "bold"),#改变图例字体大小,和字体类型
legend.text = element_text(size = 15),#改变图例内容字体大小
axis.text= element_text(size=15),#改变坐标轴内容字体大小
axis.title = element_text(size=15),#改变坐标轴标题字体大小
legend.position = c(0.2,0.8))#改变图例位置
#theme(text=element_text(size=15))#整体改变字体大小
p
library(ggrepel)#添加特定基因标签
for_label = rbind(for_label1, for_label_t)#for_label为一个data.frame文件
volcano_plot <- p +
geom_point(size = 3, shape = 1, data = for_label) +
geom_label_repel(
aes(label =rownames(for_label)),
data = for_label,
color="black"
)
volcano_plot
ggsave(plot = volcano_plot,filename = "filename.png", width = 12, height = 10)