在R语言中利用散点图坐标提取直线两侧的数据框列
Got it, let's break this down step by step. You already have your PCA biplot where each point represents a column from your original data (since the labels are the row names of prin_comp$rotation—those map directly to your original columns). Here's how to pull out the column names on either side of your line:
Step 1: Tidy up your rotation data
First, let's convert the rotation matrix into a easy-to-work-with data frame, and explicitly save your original column names as a separate column (instead of just keeping them as row names):
# Extract PC1 and PC2 values, plus add original column names as a column rot_df <- as.data.frame(prin_comp$rotation[, c(1, 2)]) rot_df$original_col <- rownames(rot_df)
Step 2: Define your line's mathematical equation
You know the line you drew—let's write it in the form y = m*x + b, where:
y= PC2 (your plot's y-axis)x= PC1 (your plot's x-axis)m= the slope of your lineb= the y-intercept of your line
For example, if your line was something like PC2 = 0.8PC1 + 0.1*, then m = 0.8 and b = 0.1.
Step 3: Filter column names by their position relative to the line
Use a simple inequality to sort points into left/right sides. The direction of the inequality depends on which side you consider "left" or "right"—test with a point you can visually confirm to get the direction right.
Get left-side column names
Suppose points where PC2 < m*PC1 + b are on the left side of your line:
# Replace m and b with your line's actual slope and intercept m <- 0.8 b <- 0.1 left_cols <- rot_df$original_col[rot_df$PC2 < (m * rot_df$PC1) + b]
Get right-side column names
Just flip the inequality to grab the other side:
right_cols <- rot_df$original_col[rot_df$PC2 > (m * rot_df$PC1) + b]
Optional: Verify with a colored plot
If you want to double-check you're picking the right points, add a "side" label to your data and redraw the plot:
# Add a column to mark which side each point is on rot_df$side <- ifelse(rot_df$PC2 < (m * rot_df$PC1) + b, "Left", "Right") # Redraw with colored points and your dashed line qplot(x = PC1, y = PC2, data = rot_df, color = side) + geom_text(aes(label = original_col)) + geom_abline(slope = m, intercept = b, linetype = "dashed") + ggtitle(my_title)
This will let you visually confirm that your code is grouping points exactly as you want.
The core idea is translating your drawn line into a mathematical rule, then using that rule to filter your rotation data—once you have that, pulling the column names is super straightforward!
内容的提问来源于stack exchange,提问作者Glubbdrubb

