text label for specific point in biplot R

1.1k views Asked by At
library('factoextra')
data('mtcars')
 pca.cars <- PCA(mtcars)
 gg <- factoextra::fviz_pca_biplot(X = pca.cars, 
                                   # samples
                                   fill.ind = mtcars$vs , col.ind = 'black',
                                   pointshape = 21, pointsize = 1.5,
                                   geom.ind = 'point', repel = T,
                                   geom.var = FALSE )
mtcars$brand <- row.names(mtcars)

In the plot gg I want a text label on the point for Valiant in mtcars$brand.

I already tried this approach, which only gives me the desired point. But I want the same plot, but with a text label on the Valiant point

gg$layers[[1]]$data <- dplyr::filter(gg$layers[[1]]$data, name == "Valiant")
gg$layers[[2]]$data <- dplyr::filter(gg$layers[[2]]$data, name == "Valiant")

Thank you!

1

There are 1 answers

0
stefan On BEST ANSWER

This could be achieved like so. Instead of extracting the coordinates via gg$layers you can

  1. Get them from the result of PCA().
  2. Put them in a dataframe
  3. Add the labels
  4. Add a geom_text layer to label the desired points
library(factoextra)
library(FactoMineR)
library(dplyr)
library(ggplot2)

pca.cars <- PCA(mtcars, graph = FALSE)
gg <- factoextra::fviz_pca_biplot(X = pca.cars, 
                                  # samples
                                  fill.ind = mtcars$vs , col.ind = 'black',
                                  pointshape = 21, pointsize = 1.5,
                                  geom.ind = 'point', repel = T,
                                  geom.var = FALSE )

# Make df with PC coordinate for each obs
d <- as.data.frame(pca.cars$ind$coord)
d$brand <- row.names(mtcars)

gg +
  geom_text(data = filter(d, brand == "Valiant"), aes(x = Dim.1, y = Dim.2, label = brand), hjust = -.1, vjust =-.1)