You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用R语言ggplot绘制多序列核苷酸占比对比柱状图?

用ggplot绘制多序列核苷酸占比对比柱状图

你的现有函数仅通过cat打印结果,无法直接用于ggplot绘图。我们需要先修改函数,让它返回结构化的数据框,再整合所有序列的结果,最后用ggplot生成对比柱状图。

1. 修改占比计算函数

修改后的函数会返回包含序列名称、核苷酸类型和对应占比的数据框,方便后续绘图:

calculate_nuc_percent <- function(sec, seq_name) {
  total_bases <- length(sec)
  data.frame(
    Sequence = seq_name,
    Nucleotide = c("A", "C", "G", "T"),
    Percentage = c(
      sum(sec == "a") / total_bases * 100,
      sum(sec == "c") / total_bases * 100,
      sum(sec == "g") / total_bases * 100,
      sum(sec == "t") / total_bases * 100
    )
  )
}

2. 准备并整合数据

假设你有5个序列向量(替换成你自己的真实数据),计算每个序列的占比并合并成总数据框:

# 示例序列(替换为你的真实数据)
seq1 <- sample(c("a", "c", "g", "t"), 100, replace = TRUE)
seq2 <- sample(c("a", "c", "g", "t"), 120, replace = TRUE, prob = c(0.3, 0.2, 0.25, 0.25))
seq3 <- sample(c("a", "c", "g", "t"), 80, replace = TRUE, prob = c(0.2, 0.3, 0.3, 0.2))
seq4 <- sample(c("a", "c", "g", "t"), 90, replace = TRUE, prob = c(0.15, 0.15, 0.4, 0.3))
seq5 <- sample(c("a", "c", "g", "t"), 110, replace = TRUE, prob = c(0.25, 0.25, 0.25, 0.25))

# 合并所有序列的占比数据
all_percents <- rbind(
  calculate_nuc_percent(seq1, "序列1"),
  calculate_nuc_percent(seq2, "序列2"),
  calculate_nuc_percent(seq3, "序列3"),
  calculate_nuc_percent(seq4, "序列4"),
  calculate_nuc_percent(seq5, "序列5")
)

3. 用ggplot绘制对比柱状图

使用分组柱状图展示各序列的核苷酸占比,同时添加数值标签增强可读性:

library(ggplot2)

ggplot(all_percents, aes(x = Sequence, y = Percentage, fill = Nucleotide)) +
  geom_col(position = position_dodge(width = 0.8), width = 0.7) +
  geom_text(aes(label = round(Percentage, 1)), 
            position = position_dodge(width = 0.8), 
            vjust = -0.5, size = 3) +
  labs(title = "各序列核苷酸占比对比",
       x = "序列",
       y = "占比 (%)",
       fill = "核苷酸") +
  theme_minimal() +
  theme(plot.title = element_text(hjust = 0.5))

关键参数说明:

  • position_dodge(width = 0.8):让同一序列下的不同核苷酸柱子并排显示
  • geom_text:在柱子上方添加保留1位小数的占比数值
  • fill = Nucleotide:用不同颜色区分四种核苷酸

内容的提问来源于stack exchange,提问作者Diego Michel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 22:20:41