当前位置:首页>java>R代码:1行代码批量生成线性回归图!

R代码:1行代码批量生成线性回归图!

  • 2026-08-25 15:11:45
R代码:1行代码批量生成线性回归图!

今天我们来学习一个超级实用的R语言技巧:如何用一行代码批量绘制所有变量的线性回归图

这个代码适用于不那么正式的分析/绘图,可以放在  附录 或者Supplementary Material 中

话不多说,咱们直接放代码:

本期的【数据+代码】可免费获取——在后台留言:20260106

library(ggplot2)library(dplyr)library(tidyr)dat <- read.csv("C:/r-workspace/data/260106data.csv", header = TRUE,sep = ",")str(dat)summary(dat)dim(dat)plot_list <- lapply(names(dat), function(var) {  ggplot(dat, aes(x = .data[[var]], y = Herbivore_damage)) +    geom_point(color = "grey30", alpha = 0.7, size = 1.5) +    geom_smooth(method = "lm", se = TRUE                color = "#e74c3c", fill = "#fadbd8"                linewidth = 0.8) +    labs(x = var, y = "Herbivore Damage") +    theme_classic() +     theme(      panel.border = element_rect(color = "gray40", linewidth = 0.6, fill = NA),      axis.line = element_line(color = "gray40", linewidth = 0.4),      axis.ticks = element_line(color = "gray40", linewidth = 0.4),      axis.title = element_text(size = 8),      axis.text = element_text(size = 7),      plot.margin = margin(4444"pt")    )})combined_plot <- wrap_plots(plot_list, ncol = 4) +   plot_annotation(    caption = "红色线条为线性回归拟合线,阴影区域为95%置信区间",    theme = theme(      plot.title = element_text(hjust = 0.5, size = 16, face = "bold"                                margin = margin(b = 10)),      plot.subtitle = element_text(hjust = 0.5, size = 12                                   color = "gray40", margin = margin(b = 15)),      plot.caption = element_text(hjust = 0.5, size = 10                                  color = "gray50", margin = margin(t = 10)),      plot.background = element_rect(fill = "white", color = NA)    )  )print(combined_plot)

效果展示:

请在微信客户端打开

最新文章

随机文章