将多个数据帧循环到ggplot

时间:2019-11-30 21:42:24

标签: r loops dataframe ggplot2

我是这门语言的新手。

我已读取多个csv文件作为数据帧,

setwd("/Users/user/go/src/Project/outputcsv2D")

file_list <- list.files(path="/Users/user/go/src/Project/outputcsv2D")

filenames <- gsub("\\.csv$","", list.files(pattern="\\.csv$"))

for(i in filenames){
  assign(i, read.csv(paste(i, ".csv", sep="")))
}

但是当我尝试遍历文件名[i]进行绘制时,

#making a list of plots
plot_list = list()
for (i in filenames) {
  p = ggplot(filenames[i], aes(y, x, colour = color)) + geom_point(alpha = .4)+xlim(0, 150)+ylim(0,150)
  plot_list[[i]] = p
}

# Save plots to png. Makes a separate file for each plot.
for (i in filenames) {
  file_name = paste("2D", i, ".png", sep="")
  png(file_name)
  print(plot_list[[i]])
  dev.off()
}

它给我这个错误:

Error: `data` must be a data frame, or other object coercible by `fortify()`, not a character vector

我尝试了get()或as.data.frame(),但似乎都没有用。 该问题的解决方案是什么?

3 个答案:

答案 0 :(得分:2)

或者walk中的read_csv + tidyverse

library(readr)
library(stringr)
library(dplyr)
library(purrr)
library(ggplot2)

walk(filenames, ~ read_csv(str_c(.x, ".csv") %>%
                      ggplot(., aes(y, x, colour = color)) +
                       geom_point(alpha = 0.4) +
                       xlim(0, 150)+
                       ylim(0,150) %>%
                  ggsave(plot = ., filename = str_c("2D", .x, ".png"))
       )

答案 1 :(得分:1)

也许您应该尝试做一个循环,以便1)读取数据帧,2)绘制和3)保存图:

for(i in filenames){
  df <- read.csv(paste(i, ".csv", sep=""))
  p = ggplot(df, aes(y, x, colour = color)) + geom_point(alpha = .4)+xlim(0, 150)+ylim(0,150)
  ggsave(plot = p, filename = paste0("2D", i, ".png"))
}

答案 2 :(得分:0)

我建议经常使用lapply()

filenamescsv <- paste0(filenames, ".csv")

lst_DF <- lapply(filenamescsv, read.csv)
gplots <- lapply(lst_DF, function(DF) ggplot(DF, aes(y, x, colour = color)) + geom_point(alpha = .4)+xlim(0, 150)+ylim(0,150))

Map(function(nam, p) {
    file_name <- paste("2D", nam, ".png", sep="")
    png(file_name)
    print(plot_list[[i]])
    dev.off()}, 
  filenames, gplots)