[英]How to automatically plot many CSV files with the same number of rows and columns?
我有許多(超過100個)具有相同表結構的csv文件,例如,所有表頭都在第4行中,它們都有6列,數據從第5行到400001,
我需要在散點圖中繪制這些數據,其中x顯示第一列(40001時間單位),其他列是Y,表示不同的變量,[如果我能夠格式化繪圖(顏色,范圍,標題,圖例,則更可取) ,...)],然后自動輸入這些csv文件並導出png或pdf或其他可能有用的東西,我同時擁有Excel和R,但我不知道如何以有效的方式進行此繪制。 (命名也很重要,它們應具有其CSV文件的名稱)
我如何可以毫不費力地做到這一點的任何想法?
謝謝
您的問題在具體細節上有點輕描淡寫,因此,我將做出一些假設,以從某種答案的框架入手。
讓我們制作一些虛假的CSV文件作為示例數據
將工作目錄設置為包含數據的文件夾...
setwd("C:/my-csv-files")
制作100個6列乘500行的數據幀(以保持快速運行)...
df <- lapply(1:100, function(i) data.frame(cbind(1:500, matrix(sample(1000), 500, 5))))
根據這些數據幀在工作目錄中制作100個csv文件...
lapply(1:length(df), function(i) write.csv(df[[i]],file=paste("df",i,"csv",sep=".")))
現在,我們可以重現您的問題,像這樣... 快速將許多CSV文件讀入R。
# create a list of all CSV files in all the folders
files <- (dir("C:/my-csv-files", recursive=TRUE, full.names=TRUE, pattern="\\.(csv|CSV)$"))
# read in the CSV files and add the filename of each file as a column to
# each dataset so we can trace back dodgy data
# so, create a function to read the CSV and get filenames
read.tables <- function(file.names, ...) {
require(plyr)
ldply(file.names, function(fn) data.frame(Filename=fn, read.csv(fn, ...)),.progress = 'text')
}
# execute function to read in data from each CSV, including file names of file that data comes from
mydata <- read.tables(files, stringsAsFactors = FALSE)
現在繪制數據 ,您說您只想要CSV文件中所有數據的一個圖...
融合為繪圖格式,這里X1
是您的時間變量, X2
至X5
是CSV文件中的其他變量
require(reshape2)
dat <- melt(mydata, id.vars = c("X1"), measure.vars = c("X2", "X3", "X4", "X5"))
這是您的時間變量與其他變量(用顏色編碼)的單個散點圖。 只是從您的問題中不清楚您要繪制的內容,所以請問另一個具有更多詳細信息的問題。
require(ggplot2)
ggplot(dat, aes(X1, value)) +
geom_point(aes(colour = factor(variable)))
現在, 將其另存為PDF或PNG ,請參見?ggsave
獲取此處的眾多選項...
ggsave(file="myplot.pdf")
ggsave(file="myplot.png")
查找這些文件的位置
getwd()
要為每個CSV文件繪制一個圖,這是一種方法
listcsvs <- lapply(files,function(i) read.csv(i, stringsAsFactors = FALSE))
names(listcsvs) <- files
require(reshape2)
require(ggplot2)
for (i in 1:length(files)) {
tmp <- melt(listcsvs[[i]], id.vars = "X1", measure.vars = c("X2", "X3", "X4", "X5"))
print(ggplot(tmp,aes(X1, value)) +
geom_point(aes(colour = factor(variable))) +
ggtitle(names(listcsvs[i]))
)
}
如果您使用的是RStudio ,則可以滾動瀏覽圖並導出要保存為PDF或PNG的圖 。
這樣就涵蓋了您問題的主要部分:
另外,您還擁有創建示例數據的代碼,可用於以后的問題中。 通常,示例數據的質量越好,您得到的答案質量就越好(如Thomas在其評論中建議的那樣)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.