科研绘图模板之小提琴分面图

2025-01-15  本文已影响0人  Bioinfor生信云

小提琴分面图(Violin plot)是一种用于展示和比较数据分布的可视化图形。它类似于箱线图,但提供了更多关于数据分布密度的信息。小提琴图的核心是小提琴形状,这种形状是通过核密度估计(KDE)来展示数据分布的密度。

小提琴图的组成:

  1. 中心标记:通常在小提琴的中心有一条线或一个点来标记数据的中位数。
  2. 箱线图:有时在小提琴内部会绘制一个简化的箱线图,表示四分位数和极值。
  3. 密度轮廓:小提琴的主体显示数据的密度,宽度表示在该值处的数据密度较高。
  4. 分面:分面是指将数据集分割成多个子集来单独展示每个子集的小提琴图,通常用于比较不同类别或组内的数据分布。

小提琴图的用途:

示例

library(ggplot2)
library(reshape2)

inputFile <- "input.txt"
outFile <- "vioplot.pdf"

# 读取输入文件
rt <- read.table(inputFile, header=TRUE, sep="\t", check.names=FALSE, row.names=1)
colnames(rt)[1] <- "Type"  # 只更改一次列名

# 差异分析
geneSig <- sapply(colnames(rt)[-1], function(gene) {
  rt1 <- rt[, c(gene, "Type")]
  test <- if (length(levels(factor(rt1$Type))) > 2) {
    kruskal.test(expression ~ Type, data = rt1)
  } else {
    wilcox.test(expression ~ Type, data = rt1)
  }
  # 根据p值赋予标记
  ifelse(test$p.value < 0.001, "***", ifelse(test$p.value < 0.01, "**", ifelse(test$p.value < 0.05, "*", "")))
})
colnames(rt)[-1] <- paste(colnames(rt)[-1], geneSig, sep="")

# 准备ggplot2绘图数据
data <- melt(rt, id.vars="Type")
colnames(data) <- c("Type", "Gene", "Expression")

# 绘制小提琴图
p1 <- ggplot(data, aes(x=Type, y=Expression, fill=Type)) +
  geom_violin() +
  geom_boxplot(width=0.2, position=position_dodge(0.9)) +
  facet_wrap(~Gene, nrow=1) +
  labs(x="Sample Type", y="Gene Expression", fill="Sample Type") +
  theme_bw() +
  theme(axis.text.x=element_text(angle=45, hjust=1))

# 输出图像
ggsave(filename=outFile, plot=p1, width=9, height=5, device="pdf")

上一篇 下一篇

猜你喜欢

热点阅读