如何用R中ggfortify包的autoplot绘制PCA旋转成分?
Hey there, let's walk through how to visualize rotated PCA results using ggfortify::autoplot() with the iris dataset. Since you already know how to get rotated PCA outputs, I'll focus on translating those results into the plot you're used to making.
Step 1: Prep your data and run base PCA
First, let's set up the data and run the initial PCA like you did before:
library(ggfortify) library(stats) # Load and prep iris data data <- iris data_dims <- data[, 1:4] data$Species <- as.factor(data$Species) # Run standard PCA pca_result <- prcomp(data_dims, center = TRUE, scale. = TRUE)
Step 2: Apply rotation and calculate rotated scores
Rotations (like varimax) target the PCA loading matrix, so we need to adjust the component scores to match. Here's how to do it with varimax rotation (you can swap in other rotation methods if needed):
# Rotate the first two principal components' loadings rotated_loadings <- varimax(pca_result$rotation[, 1:2])$loadings # Calculate rotated scores: original scores × transposed rotation matrix rotated_scores <- pca_result$x[, 1:2] %*% t(rotated_loadings)
Step 3: Update the PCA object for autoplot
autoplot() works with prcomp objects, so we'll create a modified version of our PCA result where the x (scores) and rotation (loadings) fields use the rotated values:
# Create a new prcomp object with rotated data rotated_pca <- pca_result rotated_pca$x <- rotated_scores rotated_pca$rotation <- rotated_loadings
Step 4: Plot the rotated PCA
Now you can use autoplot() exactly like you did for the original PCA—this time it'll use the rotated components:
# Generate the rotated PCA plot plot_rotated <- autoplot(rotated_pca, data = data, colour = 'Species', frame = TRUE) print(plot_rotated)
Bonus: Visualize rotated loadings
If you want to see how the variable loadings shifted after rotation, add loading labels to the plot:
autoplot(rotated_pca, data = data, colour = 'Species', frame = TRUE, loadings = TRUE, loadings.label = TRUE, loadings.label.size = 3)
The key thing to remember here is that rotation doesn't change the variance explained overall—it just reorients the components to make variable relationships easier to interpret. By updating the prcomp object's scores and loadings, you can leverage ggfortify's familiar plotting interface without rewriting all your code.
内容的提问来源于stack exchange,提问作者Dave

