最近需要手动做很多张图片,然后复制粘贴导出。于是研究了一下R的批量作图的功能。思想比较简单,就是用一个for的循环,自动完成批量作图和导出。下面以R自带的diamonds数据为例,示范一下:
#加载包
library(dplyr)
library(ggplot2)
library(scales)
getwd()
#设定路径,
setwd(D:R Project)
#################################################
#调用数据,分成子集,作图
data("diamonds")
m <- split(diamonds, diamonds$color)
length(m)
for (i in 1:length(m)) {
sub_data <- m[[i]]
#save the plot
png(filename = paste0(i, "_", ".jpg"),width = 2400,height = 1800,res = 200)
plot(sub_data$carat, sub_data$price, col = sub_data$cut)
dev.off()
}
