Search code examples
rpcaggbiplot

how can I change the legend for ggbiplot?


Actually I am trying to plot PCA by this package but when I plot the loading, I cannot change the legend as I wish (e.g. if I want to set the legend to (+)M it shows something else. what I do is as follows:

library(ggbiplot)
require(ggplot2)

data(iris)
data <- data.frame(iris[,1:4])    
ir.pca <- prcomp(data, center = TRUE, scale. = TRUE)
theta <- seq(0,2*pi,length.out = 100)
circle <- data.frame(x = cos(theta), y = sin(theta))
p <- ggplot(circle,aes(x,y)) + geom_path()

loadings <- data.frame(ir.pca$rotation, 
                       .names = row.names(ir.pca$rotation))
p + geom_text(data=loadings, 
              mapping=aes(x = PC1, y = PC2, label = .names, colour = .names)) +
  coord_fixed(ratio=1) +
  labs(x = "PC1", y = "PC2")

Now the problem is if you change the name of the variables to for example (+)C , (-)C, (*)C and (%)C then plot, it shows something else in legend instead

on the other hand, the title of the legend is .name , how to also set this to something else?


Solution

  • Is this what you mean, or am I misunderstanding:

    loadings <- data.frame(ir.pca$rotation, 
                           .names = row.names(ir.pca$rotation),
                           names2 = c("(+)C" , "(-)C", "(*)C", "(%)C"))
    
    p + geom_text(data=loadings, 
                  mapping=aes(x = PC1, y = PC2, label = names2, colour = .names)) +
      coord_fixed(ratio=1) +
      labs(x = "PC1", y = "PC2", colour="Legend Title")
    

    enter image description here

    UPDATE: Here's how to make text bold in geom_text and in the legend:

    p + geom_text(data=loadings, 
                  mapping=aes(x = PC1, y = PC2, label = names2, colour = .names),
                  fontface="bold") +
      coord_fixed(ratio=1) +
      labs(x = "PC1", y = "PC2", colour="Legend Title") +
      theme(legend.text=element_text(face="bold"))