今天在循環導出圖片時,遇到了一個問題:
使用R語言導出圖片的代碼:
1
2
3
4
|
setwd( "E://R" ) jpeg( file = "A.jpeg" ) print(plot(PEO$X, PEO$Y, pch=PEO$S)) dev.off() |
但是若是將此代碼運用到循環之中,則只會出來一張圖A.jpeg
想了好久原因,發現……..!!!!
命名方法不對啊!!!
只有一個名字!!!當然不行啊!!!
于是搜索如何循環命名…
找到了老朋友paste()
1
2
|
yourfilename= paste ( "A" ,i, ".jpeg" ,sep= "" ) jpeg( file =yourfilename) |
搞定!
補充:R語言 循環作圖
我就廢話不多說了,大家還是直接看代碼吧~
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
setwd( "C:\\Users\\Administrator\\Desktop\\pic" ) # Plot separate ggplot figures in a loop. library(ggplot2) # Make list of variable names to loop over. var_list = combn(names(iris)[1:3], 2, simplify=FALSE) # Make plots. plot_list = list() for (i in 1:3) { p = ggplot(iris, aes_string(x=var_list[[i]][1], y=var_list[[i]][2])) + geom_point(size=3, aes(colour=Species)) plot_list[[i]] = p } # Save plots to tiff. Makes a separate file for each plot. for (i in 1:3) { file_name = paste ( "iris_plot_" , i, ".tiff" , sep= "" ) tiff(file_name) print(plot_list[[i]]) dev.off() } # Another option: create pdf where each page is a separate plot. pdf( "plots.pdf" ) for (i in 1:3) { print(plot_list[[i]]) } dev.off() |
補充:R語言-循環產生變量名并賦值,應用到 ggolot2 循環作圖
問題的起源來自,想要批量出數十張組合好的圖。
實現過程中,最大的問題是如何實現:循環產生變量名,并對其將ggplot的一長段作圖代碼傳送給該變量名。
最終使用assign函數解決了
首先產生1000個字符串格式的備用變量名:
1
|
p <- c(paste0( 'p' ,1:1000)) |
接下來,只需寫個循環即可。
1
2
3
|
for (i in 1:1000) { assign(p[i],ggplot(dat,aes(x=x,y=y)) } |
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持服務器之家。如有錯誤或未考慮完全的地方,望不吝賜教。
原文鏈接:https://blog.csdn.net/sinat_41805381/article/details/80064486