如何将R语言基础绘图转换为带theme_ipsum主题的ggplot?
把Gifi::princals的基础绘图转成ggplot2(带theme_ipsum)的方法
刚好我之前处理过类似的需求,其实没有直接把基础绘图一键转成ggplot风格的简便工具——毕竟基础绘图和ggplot是两套完全独立的绘图系统。不过我们可以通过提取princals对象里的核心数据,用ggplot重新构建图形,这样就能轻松用上theme_ipsum这类美观的主题了。
下面是针对你的示例代码的完整解决方案:
步骤1:准备所需的包
除了Gifi,我们还需要ggplot2绘图包和提供theme_ipsum的hrbrthemes包:
install.packages(c("Gifi", "ggplot2", "hrbrthemes")) library(Gifi) library(ggplot2) library(hrbrthemes)
步骤2:运行你的PCA分析(保留原有代码)
这里我用Gifi包自带的winedata作为示例数据集(如果你有自己的ABC数据集,直接替换即可):
# 加载示例数据(用自己的ABC数据集可跳过) data(winedata) ABC <- winedata ABC6 <- ABC[,6:11] fitord <- princals(ABC6)
步骤3:提取绘图所需的核心数据
princals对象里已经存储了绘图需要的样本得分和变量坐标,我们把它们转成ggplot能识别的数据框:
# 提取样本的前两个主成分得分 sample_scores <- as.data.frame(fitord$scores[, 1:2]) colnames(sample_scores) <- c("Dim1", "Dim2") # 提取变量的坐标,并添加变量名 var_coords <- as.data.frame(fitord$object[, 1:2]) var_coords$Variable <- rownames(var_coords) colnames(var_coords)[1:2] <- c("Dim1", "Dim2")
步骤4:用ggplot重构图形并应用theme_ipsum
现在我们用ggplot重新绘制PCA图,同时加上theme_ipsum主题,还可以添加一些细节让图形更专业:
ggplot() + # 绘制样本点(设置透明度避免重叠) geom_point(data = sample_scores, aes(x = Dim1, y = Dim2), alpha = 0.7, size = 2, color = "#3498db") + # 绘制变量箭头(从原点出发) geom_segment(data = var_coords, aes(x = 0, y = 0, xend = Dim1, yend = Dim2), arrow = arrow(length = unit(0.2, "cm")), color = "#2c3e50", linewidth = 1) + # 添加变量标签(稍微偏移避免和箭头重叠) geom_text(data = var_coords, aes(x = Dim1 * 1.1, y = Dim2 * 1.1, label = Variable), color = "#2c3e50", fontface = "bold", size = 4) + # 标注主成分的方差贡献(让读者知道维度的解释力) xlab(paste0("Dimension 1 (", round(fitord$eigenvalues[1]/sum(fitord$eigenvalues)*100, 1), "%)")) + ylab(paste0("Dimension 2 (", round(fitord$eigenvalues[2]/sum(fitord$eigenvalues)*100, 1), "%)")) + # 应用theme_ipsum主题 theme_ipsum() + # 添加原点参考线(更清晰地看样本和变量的分布) geom_vline(xintercept = 0, linetype = "dashed", color = "gray50") + geom_hline(yintercept = 0, linetype = "dashed", color = "gray50") + # 添加标题和副标题 labs(title = "PCA Plot (Princals) with ggplot2 Style", subtitle = "Using theme_ipsum from hrbrthemes")
补充说明
- 这种重构方法的好处是完全可控:你可以自由调整点的颜色、箭头样式、标签位置等,比基础绘图灵活得多。
- 如果需要展示更多主成分维度,只需要调整提取数据时的列索引(比如
[,1:3]),再用ggplot绘制3D图或者分面图即可。
内容的提问来源于stack exchange,提问作者EB3112
相关产品推荐
相关产品推荐

