ggplot2 中类似的 xlims 和 ylims

MYa*_*208 5 r ggplot2

我正在使用以下代码生成如下所示的双标图。

library(ggfortify)
df <- iris[c(1, 2, 3, 4)]
autoplot(prcomp(df)) +
  geom_hline(yintercept = 0) +
  geom_vline(xintercept = 0)
Run Code Online (Sandbox Code Playgroud)

GG

我想知道如何简洁地获得相似的 xlims 和 ylims,以便所有四个象限的大小完全相同。

已编辑

library(ggfortify)
df <- iris[c(1, 2, 3, 4)]

autoplot(prcomp(df), data = iris, colour = 'Species',
         loadings = TRUE, loadings.colour = 'blue',
         loadings.label = TRUE, loadings.label.size = 3) +
  geom_hline(yintercept = 0) +
  geom_vline(xintercept = 0) 
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

Tje*_*ebo 4

请注意我关于在执行 PCA 之前缩放数据的评论。现在,双图实际上也可以通过多种方式进行缩放

对于你的问题。我认为最简单的方法是从 PCA 对象中提取个人的最大 x/y 坐标 - 并将它们用作限制。这是为了使用实际的 PCA 值!。缩放版本取决于您如何缩放它。一种方法见下文。

选项 1与实际 PCA 值

library(ggplot2)
library(ggfortify)

df <- iris[1:4]

res.pca <- prcomp(df, scale. = TRUE)

cmax <- res.pca$x[which.max(res.pca$x)] #get variable coordinates

autoplot(res.pca, data = iris, colour = 'Species',
         loadings = TRUE, loadings.colour = 'blue',
         loadings.label = TRUE, loadings.label.size = 3, 
         scale = FALSE) + # scale = FALSE!
  geom_hline(yintercept = 0) +
  geom_vline(xintercept = 0) +
  coord_equal(xlim = c(-cmax,cmax), ylim = c(-cmax,cmax)) 

# also using coord_equal, so that it looks equal
Run Code Online (Sandbox Code Playgroud)

由reprex 包(v0.3.0)于 2020-03-24 创建

选项 2 - 一种不同的缩放方式 该线程展示了如何在后台完成缩放(一种方式)。

由此,您可以获得缩放双图的最大限制。

library(ggplot2)
library(ggfortify)

df <- iris[1:4]

res.pca <- prcomp(df, scale. = TRUE)

choices <- 1L:2L
scale <- 1
pc.biplot <- FALSE
scores <- res.pca$x
lam <- res.pca$sdev[choices]
n <- NROW(scores)
lam <- lam * sqrt(n)
lam <- lam^scale
bi_vec <- t(t(res.pca$rotation[, choices]) * lam)
bi_ind <- t(t(scores[, choices]) / lam)

cmax <- bi_ind[which.max(bi_ind)]

autoplot(res.pca, data = iris, colour = 'Species',
         loadings = TRUE, loadings.colour = 'blue',
         loadings.label = TRUE, loadings.label.size = 3) +
  geom_hline(yintercept = 0) +
  geom_vline(xintercept = 0) +
  coord_equal(xlim = c(-cmax,cmax), ylim = c(-cmax,cmax)) 
Run Code Online (Sandbox Code Playgroud)

由reprex 包(v0.3.0)于 2020-03-24 创建