首页 > 解决方案 > 在 ggplot 中绘制 PCA 时出错 - 找不到对象或长度错误

问题描述

我正在尝试创建我的数据框(bwwq)的主要组件的双图,但我不断收到错误消息:

Error in FUN(X[[i]], ...) : object 'Location' not found

我不明白发生了什么,因为我可以在用于绘图的数据框中看到“位置”。这是数据片段(实际上有 17 个 obs 和 14 个变量)。

        Season   Location        PC1        PC2       PC3       PC4        PC5
sample1 spring  SiteA     -72.000048 33.5970759  8.873916 -2.201533  2.2538914
sample2 summer  SiteA     -71.492600 34.6823399  4.772814 -3.041415  2.1484592
sample3 fall    SiteA     -63.659760 -1.7413278 -6.658140  5.425656 -1.3978123
sample4 spring  SiteB     -57.476273 -0.3021883 -4.412755  6.253279 -2.9854573 
sample5 summer  SiteB     -64.381669  3.3609588 -3.753914  5.455738 -0.5185786
sample6 fall    SiteB       8.155867  6.5698710  5.965872 -6.753837 -1.9268316

如果我在 ggplot 调用中使用 PCAvalues$Location,我会收到另一个错误。

Error: Aesthetics must be either length 1 or the same as the data (12): shape

我一定错过了一些非常明显的东西!我究竟做错了什么?!?!

下面,我包含了我用来创建的脚本PCAvalues(基于thisthis)。当我删除时shape = Location,我得到了一个很好的 PCA 双标图,其中 Season 用颜色表示。

wq.pca <- prcomp(bwwq[,3:14])
summary(wq.pca)

# Extract PC axes for plotting
PCAvalues <- data.frame(Season = bwwq$Season, 
                        Location = bwwq$Location, 
                        wq.pca$x)

# Extract loadings of the variables
PCAloadings <- data.frame(Variables = rownames(wq.pca$rotation), 
                          wq.pca$rotation)

# Plot
ggplot(data=PCAvalues, aes(x = PC1, y = PC2, 
                           shape = Location, # I THINK THIS IS THE PROBLEM HERE 
                           colour = Season)) +
  geom_segment(data = PCAloadings, 
               aes(x = 0, y = 0,
                   xend = (PC1*5), 
                   yend = (PC2*5)), 
               arrow = arrow(length = unit(1/2, "picas")),
               color = "black") +
  geom_point(size = 3) +
  annotate("text", 
           x = (PCAloadings$PC1*5), 
           y = (PCAloadings$PC2*5),
           label = PCAloadings$Variables) +
  scale_color_brewer(palette = "Set1") +
  theme_bw()

标签: rggplot2

解决方案


推荐阅读