ggplot-带多个箭头的geom_segment()

问题描述 投票:4回答:1

我正在从事主成分分析(PCA)。我发现ggfortify效果很好,但想进行一些手动调整。

然后尝试按以下方式绘制PCA结果:

evec <- read.table(textConnection("
  PC1        PC2        PC3
  -0.5708394 -0.6158420 -0.5430295
  -0.6210178 -0.1087985  0.7762086
  -0.5371026  0.7803214 -0.3203424"
), header = TRUE, row.names = c("M1", "M2", "M3"))

res.ct <- read.table(textConnection("
  PC1        PC2        PC3
  -1.762697 -1.3404825 -0.3098503
  -2.349978 -0.0531175  0.6890453
  -1.074205  1.5606429 -0.6406848
  2.887080 -0.7272039 -0.3687029
  2.299799  0.5601610  0.6301927"
), header = TRUE, row.names = c("A", "B", "C", "D", "E"))

require(ggplot2)
require(dplyr)
gpobj <- 
  res.ct %>%
  ggplot(mapping = aes(x=PC1, y=PC2)) +
  geom_point(color="grey30") +
  annotate(geom="text", x=res.ct$PC1*1.07, y=res.ct$PC2*1.07,
           label=rownames(res.ct))

for (i in 1:nrow(evec))
{
  PCx <- evec[i,1]
  PCy <- evec[i,2]
  axisname <- rownames(evec)[[i]]
  gpobj <- gpobj +
    geom_segment(
      data = evec[i,],
      aes(
        x = 0, y = 0,
        xend = PC1, yend = PC2
        # xend = PCx, yend = PCy  #not work as intended
      ),
      arrow = arrow(length = unit(4, "mm")),
      color = "red"
    ) +
    annotate(
      geom = "text",
      x = PCx * 1.15, y = PCy * 1.15,
      label = axisname,
      color = "red"
    )
}
gpobj

该代码运行良好,但是当我尝试使用带注释的行xend = PCx, yend = PCy而不是xend = PC1, yend = PC2时,它不能按我预期的那样很好地工作,它不会显示所有箭头。

xend = PC1, yend = PC2效果很好:

<<

xend = PCx, yend = PCy不:

<<

问题:当起点和终点由环境变量指定而不是由geom_segment()中的变量名称引用时,为什么data =不保留上一个箭头?

我正在从事主成分分析(PCA)。我发现ggfortify效果很好,但想进行一些手动调整。然后在这里尝试绘制PCA结果,如下所示:evec

r ggplot2
1个回答
0
投票
这表示PCx / PCy的值在

外部

for循环中求值。至此,它们对应于它们为i = 3取的最后一个值,这就是为什么只有一个箭头段(实际上是三个箭头叠置)可见的原因。 xend = PCx, yend = PCy移到aes(...)之外应该可以达到您想要的外观。
© www.soinside.com 2019 - 2024. All rights reserved.