rggplot2cluster-analysispcaggfortify

How to get Principal Component Data in PAM in R


I create a graph using autoplot function using mtcars data and get graph like this

enter image description here

here my code:

library(cluster)
library(NbClust)
library(ggplot2)
library(ggfortify)
x <- mtcars
number.cluster <- NbClust(x, distance = "euclidean", min.nc = 1, max.nc = 5, method = "complete", index = "ch")
best.cluster <- as.numeric(number.cluster$Best.nc[1])
x.pam <- pam(x, best.cluster)
autoplot(x.pam, data = x, frame = T) + ggtitle("PAM MTCARS")

my question is how do i get PC1 & PC2 data Coordinate based on this graph? thank you


Solution

  • You can use layer_data() to get the data used for a ggplot object:

    p <- autoplot(x.pam, data = x, frame = T) + ggtitle("PAM MTCARS")
    layer_data(p, 1L) # coordinates of all points
    layer_data(p, 2L) # coordinates of points that contribute to polygons