# 安装所需的包,如果已经安装可以跳过这一步
install.packages("ggplot2")
install.packages("ggrepel")
# 加载包
library(ggplot2)
library(ggrepel)
# 假设你的数据框叫做 data
# data <- read.csv("你的数据文件.csv") # 如果你的数据在CSV文件中
# 计算-log10(P值)
data$neg_log10_pvalue <- -log10(data$P.Value)
# 定义显著性阈值
pvalue_thresh <- 0.05
logfc_thresh <- 1
# 定义一个新列来表示显著性(你可以根据需要自定义这些颜色)
cluster5.markers$threshold <- with(cluster5.markers,
factor(ifelse(p_val < pvalue_thresh & abs(avg_log2FC) > logfc_thresh,
ifelse(avg_log2FC >= logfc_thresh, "up", "down"),
"not_significant"),
levels = c('up', 'down', 'not_significant')))
# 绘制火山图
volcano_plot <- ggplot(cluster5.markers, aes(x = avg_log2FC, y = neg_log10_pvalue, color = threshold)) +
geom_point(size = 1.5, alpha = 0.6) + # 调整点的大小和透明度
geom_vline(xintercept = c(logfc_thresh,-logfc_thresh), linetype = "dashed", color = "black")+
geom_hline(yintercept = -log10(pvalue_thresh), linetype = "dashed", color = "black") + # 添加横线
labs(x = "Log2 Fold Change", y = "neg_log10_pvalue", title = "Volcano Plot") + # 添加坐标轴标签和标题
scale_color_manual(values = c(not_significant="grey", up = "red", down = "green"))+ # 定义颜色
theme_minimal() # 使用简洁的主题
# 打印火山图
print(volcano_plot)
# 如果你想要为显著的基因添加标签,上调基因前五个
top_up_genes <- cluster5.markers[cluster5.markers$avg_log2FC > logfc_thresh & cluster5.markers$p_val < pvalue_thresh, ]
top_up_genes <- top_up_genes[order(top_up_genes$p_val), ]
top_up_genes <- top_up_genes[1:5, ]
# 筛选下调最显著的五个基因
top_down_genes <- cluster5.markers[cluster5.markers$avg_log2FC < -logfc_thresh & cluster5.markers$p_val < pvalue_thresh, ]
top_down_genes <- top_down_genes[order(top_down_genes$p_val), ]
top_down_genes <- top_down_genes[1:5, ]
###将筛选出的基因放回之前的数据集
cluster5.markers$jiyin[which(cluster5.markers$label == "RPS27")] <- "RPS27"
cluster5.markers$jiyin[which(cluster5.markers$label == "RPL13A")] <- "RPL13A"
cluster5.markers$jiyin[which(cluster5.markers$label == "RPL13")] <- "RPL13"
cluster5.markers$jiyin[which(cluster5.markers$label == "RPS18")] <- "RPS18"
cluster5.markers$jiyin[which(cluster5.markers$label == "RPL3")] <- "RPL3"
# 绘制带有基因标签的火山图
volcano_plot_with_labels <- volcano_plot + geom_text_repel(aes(label = jiyin), size = 3, point.padding = 0.5, box.padding = 0.5)
# 打印带有基因标签的火山图
print(volcano_plot_with_labels)