如何在R语言自定义graphplotter函数中添加png/pdf/jpeg图形导出功能
R语言自定义绘图函数多格式导出实现
需求说明
需要将png/pdf/jpeg格式的导出逻辑封装到现有自定义绘图函数graphplotter中,同时保留原有绘图逻辑不变。
修改后完整代码
测试数据集
# 数据集 Gen <- c('M','M','M','M','F','F','F','F','M','M','M','M','F','F','F','F') Site <- rep('FRX',length(Gen)) Type <- c('L','L','L','L','L','L','L','L','R','R','R','R','R','R','R','R') UID <- c(1001,1002,1003,1004,1001,1002,1003,1004,1001,1002,1003,1004,1001,1002,1003,1004) Time_1 <- c(100.78,112.34,108.52,139.19,149.02,177.77,79.18,89.10,106.78,102.34,128.52,119.19,129.02,147.77,169.18,170.11) Time_2 <- c(150.78,162.34,188.53,197.69,208.07,217.76,229.48,139.51,146.87,182.54,189.57,199.97,229.28,247.73,269.91,249.19) Time_3 <- c(250.78,262.34,288.53,297.69,308.07,317.7,329.81,339.15,346.87,382.54,369.59,399.97,329.28,347.73,369.91,349.19) Time_4 <- c(240.18,232.14,258.53,276.69,338.07,307.74,359.16,339.25,365.87,392.48,399.97,410.75,429.08,448.39,465.15,469.33) Time_5 <-c(270.84,282.14,298.53,306.69,318.73,327.47,369.63,389.59,398.75,432.18,449.78,473.55,494.85,509.39,515.52,539.23) df <- data.frame(Gen,Site,Type,UID,Time_1,Time_2,Time_3,Time_4,Time_5)
修改后的graphplotter函数
library(tidyr) library(ggplot2) graphplotter <- function(x, output_format = "png", filename = "turbidity-vs-time", width = 10, height = 8, dpi = 300){ # 原有绘图逻辑,先生成ggplot对象 plot_obj <- x %>% gather(., time, turbidity, Time_1:Time_5, factor_key=TRUE) %>% mutate(label = (paste0(Gen, "-", Type))) %>% ggplot(aes(color = label)) + geom_point(aes(time, turbidity, shape = label, group = label)) + geom_line(aes(time, turbidity, group = label)) + facet_wrap(~UID) + theme( legend.position = c(1, 1), legend.justification = c("right", "top"), legend.box.just = "right", legend.margin = margin(1, 1, 1, 1), legend.text = element_text(size = 7) ) # 新增导出逻辑 # 拼接完整文件名 full_filename <- paste0(filename, ".", output_format) # 根据指定格式打开对应图形设备 if(output_format == "png"){ png(filename = full_filename, width = width, height = height, units = "in", res = dpi) } else if(output_format == "pdf"){ pdf(file = full_filename, width = width, height = height) } else if(output_format %in% c("jpeg", "jpg")){ jpeg(filename = full_filename, width = width, height = height, units = "in", res = dpi) } else { stop("仅支持png、pdf、jpeg三种导出格式") } # 打印图形对象到打开的设备中 print(plot_obj) # 关闭设备完成导出 dev.off() # 可选:返回图形对象,方便后续调整 return(invisible(plot_obj)) }
使用示例
# 默认导出png格式,文件名为turbidity-vs-time.png graphplotter(df) # 导出pdf格式 graphplotter(df, output_format = "pdf", filename = "浊度随时间变化趋势") # 导出jpeg格式,自定义图片尺寸和分辨率 graphplotter(df, output_format = "jpeg", width = 12, height = 9, dpi = 600)
说明
- 函数内新增了可配置参数,支持自定义导出格式、文件名、图片尺寸、分辨率,适配不同场景需求
- 必须在函数内显式
printggplot对象,否则图形不会写入到导出设备中 - 如果不需要静默导出,可以去掉
return前的invisible关键字,调用函数时会同时在RStudio的Plots面板展示图形
内容的提问来源于stack exchange,提问作者nasa313
相关产品推荐
相关产品推荐

