ggplot2是否有通用模板简化代码?求简化工具及替代绘图包
关于生存曲线绘图的疑问
我是ggplot2新手,绘制如下生存曲线需编写30行代码,深感繁琐。现咨询以下问题:
- 是否存在可创建类似下图的简单通用绘图模板?
- 有无可简化ggplot2使用的工具包?
- 有无对普通用户而言比ggplot2简单、但比base R绘图更具自定义性的替代绘图包?

原绘图代码
library(dplyr) library(ggplot2) library(MASS) library(survival) lung1 <- lung %>% mutate(time1 = ifelse(time >= 500, 500, time)) %>% mutate(status1 = ifelse(status == 2 & time >= 500, 1, status)) weibCurve <- function(time, survregCoefs) {exp(-(time/exp(survregCoefs[1]))^exp(-survregCoefs[2]))} fit1 <- survreg(Surv(time1, status1) ~ 1, data = lung1) lung1.survfit <- survfit(Surv(time1, status1) ~ 1, data = lung1) lung1.df <- data.frame(time = lung1.survfit$time, survival = lung1.survfit$surv, upper_95 = lung1.survfit$upper, lower_95 = lung1.survfit$lower) # generate simulation paths n_simulations <- 50 simPaths <- data.frame(x = seq(from = 500, to = 1000, by = 5)) simPathList <- lapply(1:n_simulations, function(i) { newCoef <- MASS::mvrnorm(n = 1, fit1$icoef, vcov(fit1)) y <- weibCurve(simPaths$x, newCoef) simPaths[[paste0("y", i)]] <- y simPaths }) simPaths_df <- Reduce(function(x, y) merge(x, y, by = "x", all = TRUE), simPathList) simPaths_df_long <- pivot_longer(simPaths_df, -x, names_to = "sim", values_to = "survival") fit_km <- summary(survfit(Surv(time, status) ~ 1, data = lung)) plot_km <- data.frame(x = fit_km$time, y = fit_km$surv) lung1.df %>% ggplot(aes(x = time, y = survival)) + geom_line(aes(x = x, group = sim, color = "Simulations"), data=simPaths_df_long) + geom_ribbon(aes(ymin = lower_95, ymax = upper_95, fill = "Confidence Interval"), alpha = 0.2) + scale_fill_manual(values = c("Confidence Interval" = "grey50"), name = NULL) + geom_line(aes(y = survival, color = "K-M actual data to period 500"), linewidth = 1) + scale_x_continuous(limits = c(0, 1500)) + scale_y_continuous(limits = c(0, 1), expand = c(0, 0.05)) + labs(x = "Time", y = "Survival probability", color = NULL) + theme_classic() + stat_function(fun = weibCurve, args = list(survregCoefs = fit1$icoef), aes(color = "Weibull distribution fit"), size = 1, n = 1000) + scale_color_manual( values = c( "K-M actual data to period 500"="blue", "K-M actual data after period 500"="black", "Weibull distribution fit"="red", "Simulations"="lightblue", "Confidence Interval"="grey50") ) + labs(color = NULL) + geom_step(data = plot_km %>% filter(x > 500), aes(x = x, y = y, color = "K-M actual data after period 500"), size = 1, alpha = 0.7) + theme(legend.position = c(0.95, 0.95), legend.justification = c(1, 1), legend.title.align = 0.5, legend.box.spacing = unit(0.3, "lines"), legend.margin = margin(t = 0, r = 0, b = 0, l = 0), legend.title = element_text(size = 12), legend.text = element_text(size = 10))
问题解答
1. 通用生存曲线绘图模板
可以把现有代码封装成可复用的函数模板,将数据处理、模型拟合、绘图逻辑打包,后续只需传入核心参数即可生成类似图表:
plot_custom_survival <- function(data, time_col, status_col, truncate_at = 500, n_sim = 50) { # 数据预处理 df <- data %>% mutate(time1 = ifelse(.data[[time_col]] >= truncate_at, truncate_at, .data[[time_col]]), status1 = ifelse(.data[[status_col]] == 2 & .data[[time_col]] >= truncate_at, 1, .data[[status_col]])) # 模型拟合 fit_weib <- survreg(Surv(time1, status1) ~ 1, data = df) surv_fit <- survfit(Surv(time1, status1) ~ 1, data = df) surv_df <- data.frame(time = surv_fit$time, survival = surv_fit$surv, upper_95 = surv_fit$upper, lower_95 = surv_fit$lower) # 生成模拟路径 weibCurve <- function(time, coefs) exp(-(time/exp(coefs[1]))^exp(-coefs[2])) sim_x <- seq(truncate_at, 1000, by = 5) sim_paths <- lapply(1:n_sim, function(i) { new_coef <- MASS::mvrnorm(1, fit_weib$icoef, vcov(fit_weib)) data.frame(x = sim_x, survival = weibCurve(sim_x, new_coef), sim = i) }) %>% bind_rows() # 完整K-M曲线数据 full_km <- summary(survfit(Surv(.data[[time_col]], .data[[status_col]]) ~ 1, data = data)) full_km_df <- data.frame(x = full_km$time, y = full_km$surv) # 绘图 ggplot(surv_df, aes(x = time, y = survival)) + geom_line(aes(x = x, group = sim, color = "Simulations"), data = sim_paths) + geom_ribbon(aes(ymin = lower_95, ymax = upper_95, fill = "Confidence Interval"), alpha = 0.2) + geom_line(aes(color = "K-M actual data to period 500"), linewidth = 1) + stat_function(fun = weibCurve, args = list(coefs = fit_weib$icoef), aes(color = "Weibull distribution fit"), size = 1, n = 1000) + geom_step(data = full_km_df %>% filter(x > truncate_at), aes(x = x, y = y, color = "K-M actual data after period 500"), size = 1, alpha = 0.7) + scale_fill_manual(values = c("Confidence Interval" = "grey50"), name = NULL) + scale_color_manual(values = c( "K-M actual data to period 500" = "blue", "K-M actual data after period 500" = "black", "Weibull distribution fit" = "red", "Simulations" = "lightblue" ), name = NULL) + scale_x_continuous(limits = c(0, 1500)) + scale_y_continuous(limits = c(0, 1), expand = c(0, 0.05)) + labs(x = "Time", y = "Survival probability") + theme_classic() + theme(legend.position = c(0.95, 0.95), legend.justification = c(1, 1), legend.margin = margin(0,0,0,0), legend.text = element_text(size = 10)) } # 使用示例 plot_custom_survival(lung, "time", "status")
该模板可直接复用,修改参数即可适配不同数据集。
2. 简化ggplot2的工具包
- survminer:专门针对生存分析可视化,核心函数
ggsurvplot()可一键生成带置信区间、风险表的K-M曲线,还支持添加拟合分布曲线,大幅减少代码量。 - ggpubr:封装了ggplot2常用绘图逻辑,语法简洁,快速生成高质量统计图表。
- ggthemes:提供现成的美观主题,无需手动调整
theme()参数。 - patchwork:简化多ggplot图的拼接,语法直观,替代复杂的
gridExtra操作。
3. 替代绘图包
- plotly:交互式绘图工具,语法比ggplot2更直观,生成的生存曲线支持交互查看数值,自定义性强于base R,无需记忆复杂图层逻辑。
- lattice:老牌绘图包,语法简单,支持分面等自定义功能,输出图表比base R更美观规范。
- echarts4r:基于ECharts的R接口,代码简洁,生成交互式生存曲线,自定义选项丰富,适合需要交互展示的场景。
- ggvis:语法接近ggplot2但更简洁,支持交互式绘图,适合快速出图。
内容的提问来源于stack exchange,提问作者Village.Idyot
相关产品推荐
相关产品推荐

