在ggplot中绘制PCA时出错-找不到对象或长度错误

时间:2018-12-12 04:21:34

标签: r ggplot2

我正在尝试创建数据帧(bwwq)的主要成分的双图,但是我一直收到错误消息:

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

我不知道发生了什么,因为我可以在用于绘图的数据框中看到“位置”。这是数据片段(实际上有17obs和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()

0 个答案:

没有答案