如何使用 ggbiplot 使双标图名称更清晰

how to make the biplot name more clear using ggbiplot

我有一个数据可以从这里下载 https://gist.github.com/anonymous/5f1135e4f750a39b0255

我尝试使用以下函数用 ggbiplot 绘制 PCA

data <- read.delim("path to the data.txt")
data.pca <- prcomp (data, center = TRUE, scale =TRUE)
library(ggbiplot)
g <- ggbiplot(data.pca, obs.scale =1, var.scale=1, ellipse = TRUE, circle=TRUE)
g <- g + scale_color_discrete(name='')
g <- g + theme(legend.direction = 'horizontal', legend.position = 'top')
print(g)

然而,很难看到双标线的名称,

有什么方法可以让它更清楚或更好地展示吗?

我认为一种使其更清晰的方法是使用 varname.sizevarname.adjust 参数调整标签的大小和位置。然而,由于存在很多变数,它看起来仍然很拥挤。通过增加箭头的长度(类似于 stats::biplot()),使其看起来更好(imo)

# install ggbiplot
#require(devtools)
#install_github('ggbiplot','vqv')

library(httr) 
library(ggbiplot)

# read data
url <- "https://gist.githubusercontent.com/anonymous/5f1135e4f750a39b0255/raw/data.txt"
dat <- read.table(text=content(GET(url), as="text"), header=TRUE)

# pca 
data.pca <- prcomp (dat, center = TRUE, scale =TRUE)

# original plot + increase labels size and space from line
p <- ggbiplot(data.pca, obs.scale=1, 
              var.scale=1, circle=F, 
              varname.size=4, varname.adjust=2)  
p

# use coord_equal() to change size ratio of plot (excludes use of circle)
p <- p + coord_equal(1.5) + theme_classic()
p

要延长箭头,需要重新计算 x 和 y 坐标。然后您可以使用这些来编辑相关的 grobs,并更改任何其他参数(颜色、大小、旋转等)。 (您可以采用整个 ggplotGrob(p) 方法,但只需使用下面的 grid.edit()。)

# function to rescale the x & y positions of the lines and labels
f <- function(a0, a1, M=M)
      {
      l <- lapply(as.list(environment()), as.numeric)
      out <- M* (l$a1 - l$a0) + l$a0
      grid::unit(out, "native")
      }  

# get list of grobs in current graphics window
grobs <- grid.ls(print=FALSE)  

# find segments grob for the arrows
s_id <- grobs$name[grep("segments", grobs$name)]

# edit length and colour of lines
seg <- grid.get(gPath(s_id[2]))     
grid.edit(gPath(s_id[2]),  
            x1=f(seg$x0, seg$x1, 2), 
            y1=f(seg$y0, seg$y1, 2),
            gp=gpar(col="red"))


# find text grob for the arrow labels
lab_id <- grobs$name[grep("text", grobs$name)]

# edit position of text, and rotate and colour labels
seg2 <- grid.get(gPath(lab_id)) 
grid.edit(gPath(lab_id),  
            x=f(seg$x0, seg2$x, 2), 
            y=f(seg$y0, seg2$y, 2),
            rot=0,
            gp=gpar(col="red"))

主观的,如果这会使它变得更好,也许使用 biplot() 甚至定义一个新函数会更容易