如何解决factoextra包中fviz_pca_biplot的标签重叠问题
问题说明
使用factoextra包的fviz_pca_biplot()绘制PCA双图时,变量标签出现重叠。尝试添加geom_label_repel()命令:
+ geom_label_repel(aes(label = names, label.size = 6), min.segment.length = 0.5)
触发以下报错:
Don't know how to automatically pick scale for object of type
. Defaulting to continuous.
Error ingeom_label_repel():
! Problem while computing aesthetics.
ℹ Error occurred in the 10th layer.
Caused by error incompute_aesthetics():
! Aesthetics are not valid data columns.
✖ The following aesthetics are invalid:
✖label = names
ℹ Did you mistype the name of a data column or forget to addafter_stat()?
Runrlang::last_error()to see where the error occurred.
Warning message:
In geom_label_repel(aes(label = names, label.size = 6), min.segment.length = 0.5):
Ignoring unknown aesthetics: label.size
简便解决方案
方法1:利用fviz_pca_biplot自带的避让功能
这是最省事的方法,fviz_pca_biplot()内置了ggrepel的标签避让逻辑,直接设置参数即可:
fviz_pca_biplot(your_pca_object, repel = TRUE, # 开启标签自动避让,解决重叠 var_labels_size = 6 # 设置变量标签字号 )
repel = TRUE会自动处理标签重叠,无需额外添加图层。var_labels_size是官方提供的调整变量标签大小的参数,替代报错里的label.size。
方法2:正确调用geom_label_repel(自定义需求场景)
如果需要更灵活的标签控制,要修正之前代码的两个错误:
- 变量标签的列名是
name(不是names),这是fviz_pca_biplot生成数据中的默认列名。 - 调整标签字号用
size参数,label.size是控制标签边框粗细的,不是字号。
示例代码:
fviz_pca_biplot(your_pca_object) + geom_label_repel( data = . %>% filter(..class.. == "var"), # 只对变量标签生效,不影响样本点 aes(label = name, size = 6), min.segment.length = 0.5, show.legend = FALSE # 去掉大小对应的图例,保持整洁 )
方法3:手动调整或隐藏部分标签
如果部分标签实在难以避让,可以手动隐藏不重要的标签,或者调整显示位置:
fviz_pca_biplot(your_pca_object, repel = TRUE, var_labels = c("变量1", "", "变量3", ...) # 用空字符串隐藏指定标签 )
内容的提问来源于stack exchange,提问作者behrooz Akbari

