如何在gratia包中不修改数据框变量名修改绘图标题与轴标签
不修改数据框变量名的前提下修改gratia绘图的标签与标题
方法1:在draw()函数中直接指定自定义标签映射
通过draw()的labeller参数,结合ggplot2::labeller定义变量和光滑项的显示标签,无需后续修改子图:
library(patchwork) library(gratia) library(ggplot2) set.seed(123) data <- data.frame( y = rnorm(100), x1 = rnorm(100), x2 = rnorm(100) ) model <- gam(y ~ s(x1) + s(x2), data = data) # 定义标签映射 var_labels <- c( x1 = "素食人数", x2 = "血液中铁含量" ) smooth_title_labels <- c( "s(x1)" = "s(素食人数)", "s(x2)" = "s(血液中铁含量)" ) # 绘图时指定labeller smooth_plot <- draw(model, ci_col = "steelblue", smooth_col = "blue", grouped_by = TRUE, labeller = labeller( # 映射x轴变量标签 variable = ~ var_labels[.x], # 映射光滑项标题 smooth = ~ smooth_title_labels[.x] )) smooth_plot <- smooth_plot + plot_layout(nrow = 1, ncol = 2) print(smooth_plot)
方法2:遍历patchwork子图手动修改标签
如果需要更灵活的调整,可以直接提取patchwork中的每个子图,逐个修改轴标签和标题后重新组合:
library(patchwork) library(gratia) library(purrr) library(ggplot2) set.seed(123) data <- data.frame( y = rnorm(100), x1 = rnorm(100), x2 = rnorm(100) ) model <- gam(y ~ s(x1) + s(x2), data = data) smooth_plot <- draw(model, ci_col = "steelblue", smooth_col = "blue", grouped_by = TRUE) # 定义标签映射表 x_label_map <- c("x1" = "素食人数", "x2" = "血液中铁含量") title_map <- c("s(x1)" = "s(素食人数)", "s(x2)" = "s(血液中铁含量)") # 遍历每个子图修改标签 modified_plots <- map(smooth_plot$plots, function(sub_plot) { # 获取当前子图的x轴标签和标题 current_x <- sub_plot$labels$x current_title <- sub_plot$labels$title # 替换标签并返回修改后的子图 sub_plot + labs( x = x_label_map[current_x], title = title_map[current_title] ) }) # 重新组合为patchwork并设置布局 smooth_plot_modified <- wrap_plots(modified_plots) + plot_layout(nrow = 1, ncol = 2) print(smooth_plot_modified)
两种方法都无需修改原始数据框的变量名:方法1简洁高效,适合批量统一替换;方法2灵活性强,适合对特定子图做额外调整。
内容的提问来源于stack exchange,提问作者F3d33
相关产品推荐
相关产品推荐

