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

ggplot绘制PCA图报错:需从色调调色板请求至少一种颜色

解决ggplot绘制PCA图时的Error: Must request at least one colour from a hue palette.错误

问题场景

运行以下PCA绘图代码时触发报错:

#pdf(file="pca.mouse.control.pdf")
#performing PCA using top 500 varying genes
pcaData<-plotPCA(logTrans, intgroup=c("condition","time"), ntop=3000,returnData=TRUE) #top 1000
percentVar<-round(100*attr(pcaData,"percentVar")) #percent variance caused by pca1, pca2 rounded to a percentage
#coloring the points by Condition and shaping the points by Sex
ggplot(pcaData, aes(PC1, PC2, color=condition, shape=time))+
  geom_point(size=3)+
  xlab(paste0("PC1: ",percentVar[1],
              "%variance"))+
  ylab(paste0("PC2: ",percentVar[2],
              "%variance"))+
  coord_fixed()

报错信息:

Error: Must request at least one colour from a hue palette.

上下文代码:

ddsHTSeq<-DESeqDataSetFromHTSeqCount(sampleTable=sampleTable, directory=directory, design=~treatment_group+time) 
ddsHTSeq<- estimateSizeFactors(ddsHTSeq)
logTrans<- vst(ddsHTSeq) #normalized counts

已知pcaData中的condition列全部为<NA>。

报错原因

ggplot尝试根据condition列给散点分配颜色,但该列全是缺失值(NA),没有可用于区分的分组类别,导致颜色调色板无法生成有效映射,触发报错。

解决方案

1. 修正分组列名(最可能的解决方式)

从上下文代码看,DESeq2设计矩阵用的是treatment_group而非condition,说明sampleTable里的分组列应该是treatment_group。需同步修改plotPCA和ggplot中的分组参数:

修正后的代码:

# 使用treatment_group作为颜色分组列,与design矩阵保持一致
pcaData<-plotPCA(logTrans, intgroup=c("treatment_group","time"), ntop=3000,returnData=TRUE)
percentVar<-round(100*attr(pcaData,"percentVar"))
ggplot(pcaData, aes(PC1, PC2, color=treatment_group, shape=time))+
  geom_point(size=3)+
  xlab(paste0("PC1: ",percentVar[1],"% variance"))+
  ylab(paste0("PC2: ",percentVar[2],"% variance"))+
  coord_fixed()

2. 补全condition列的缺失值(如果确实需要用该列)

如果condition是你需要的分组列,但数据全为NA,需要先补全sampleTable中的condition数据,重新构建ddsHTSeq对象并做标准化,再重新生成PCA数据。

3. 临时移除颜色映射(快速验证PCA结果)

如果只是想先看PCA分布情况,可暂时去掉color映射:

ggplot(pcaData, aes(PC1, PC2, shape=time))+
  geom_point(size=3)+
  xlab(paste0("PC1: ",percentVar[1],"% variance"))+
  ylab(paste0("PC2: ",percentVar[2],"% variance"))+
  coord_fixed()

验证步骤

运行绘图代码前,先检查PCA数据的分组列是否有效:

# 查看pcaData的结构
str(pcaData)
# 查看分组列的类别分布
table(pcaData$treatment_group) # 对应修正后的分组列

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 21:43:29