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

如何用R的ggplot2绘制蛋白质凝胶组分丰度谱图?

解决ggplot2绘制蛋白质丰度谱的问题

嘿,我完全懂你的困扰——ggplot2对数据格式有特定要求,咱们一步步来搞定这个问题:

第一步:把宽格式数据转成ggplot友好的长格式

你的plotdata是宽格式(每个组分单独占一列),但ggplot2更适配长格式(每一行对应一个蛋白质的一个组分丰度值)。咱们用tidyr包的pivot_longer()函数来完成转换:

首先加载所需工具包(tidyverse包含了ggplot2和tidyr,一次加载就够):

# 第一次用的话先安装包
# install.packages("tidyverse")
library(tidyverse)

接着转换数据格式:

# 先还原你的示例数据
IDs<- c("prot1", "prot2", "prot3", "prot4")
fraction1 <- c(3,4,2,4)
fraction2<- c(1,2,4,1)
fraction3<- c(6,4,6,2)
plotdata<-data.frame(IDs, fraction1, fraction2, fraction3)

# 转成ggplot喜欢的长格式
plotdata_long <- plotdata %>%
  pivot_longer(cols = starts_with("fraction"),  # 选中所有以fraction开头的列
               names_to = "Fraction",          # 新增列:存储组分名称
               values_to = "Abundance")        # 新增列:存储对应丰度值

转换后的长格式数据示例:

# A tibble: 12 × 3
   IDs   Fraction  Abundance
   <chr> <chr>         <dbl>
 1 prot1 fraction1         3
 2 prot1 fraction2         1
 3 prot1 fraction3         6
 4 prot2 fraction1         4
 5 prot2 fraction2         2
 6 prot2 fraction3         4
...

第二步:用ggplot2绘制丰度谱

现在数据格式正确了,咱们可以轻松画出所有蛋白质的丰度折线图:

ggplot(plotdata_long, aes(x = Fraction, y = Abundance, color = IDs, group = IDs)) +
  geom_line(size = 1) +  # 绘制折线,调整线条粗细
  geom_point(size = 2) + # 给每个数据点加标记,让趋势更清晰
  labs(title = "蛋白质凝胶组分丰度谱",
       x = "凝胶组分",
       y = "丰度值",
       color = "蛋白质ID") +
  theme_minimal() +      # 用清爽的极简主题
  theme(plot.title = element_text(hjust = 0.5)) # 让标题居中显示

关键代码解释:

  • aes(x = Fraction, y = Abundance):指定x轴对应凝胶组分,y轴对应丰度值
  • color = IDs, group = IDs:用颜色区分不同蛋白质,group参数确保每个蛋白的点被正确连成长线(只写color也能自动分组,但显式标注更清晰)
  • geom_line()和geom_point():组合使用折线和点标记,让丰度变化趋势更直观
  • labs()和theme():自定义图的标题、坐标轴标签和整体样式

这样就能在同一张图里清晰展示所有蛋白质的丰度谱了,完全不会出现Excel那种因数据顺序导致的bug~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:29:10