当我们面对大量数据画图时,我们往往采用循环出图的方式,以下我将介绍三种方式:
1.数据在一张表上
数据在一张表上,我们想对每一列的数据进行画图,比方说画直方图
我们直接对列进行遍历:
for (i in 1:6) {
p = ggplot(repeat2,aes(x=repeat2[,i]))+
geom_histogram(binwidth = 0.1 ,color="black",fill="white",
boundary=14)+
scale_x_continuous(breaks=seq(14, 26, 0.5))+
scale_y_continuous(breaks = seq(0,100,5))
print(p)
}
此时注意,ggplot遍历出图和只花一张图是不一样的,只画一张图输出 p 即可,遍历画图需要写 print(p)
2.多个文件画图
这一块我们可以分两种情况,
(1).文件夹遍历
一种是直接对文件夹直接遍历(里面没有其他文件)
上图为文件夹中各文件的情况
上图为每个文件中数据的情况
for (i in dir('/home/dir')) {
dat = read.csv(i)
p = ggplot(dat,aes(x=dat[,1]))+
geom_histogram(binwidth = 0.1 ,color="black",fill="white",
boundary=14) ##设置组边界
print(p)
}
(2).文件list
或者你将你的文件作成一个data.frame
下图为每个文件具体情况
setwd('dir')
for (i in lt$file) {
data <- read.csv( i, header = T)
p = ggplot(data,aes(x= data[,1]))+
geom_histogram(binwidth = 0.1 ,color="black",fill="white",
boundary=14)+ ##设置组边界
scale_x_continuous(breaks=seq(14, 26, 0.5))+ ##设置x坐标轴刻度
scale_y_continuous(breaks = seq(0,100,5)) ##y坐标轴刻度
print(p)
}
因为你将文件名做成data,frame,那么以后改文件名也方便些
参考:
https://zhuanlan.zhihu.com/p/101520563?utm_source=wechat_session
网友评论