magick0108
magick0108

Reputation: 11

Looping over multiple data frames to ggplot

I am very new to the language.

I have read in multiple csv files as dataframes,

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="")))
}

but when I try to loop over the filenames[i] to plot,

#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()
}

it is giving me this error :

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

I have tried get() or as.data.frame() but neither seemed to work. What would be the solution for this problem?

Upvotes: 1

Views: 774

Answers (3)

akrun
akrun

Reputation: 886938

Or walk + read_csv from 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"))
       )

Upvotes: 2

Cole
Cole

Reputation: 11255

I recommend using lapply() a lot.

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)

Upvotes: 0

dc37
dc37

Reputation: 16178

Maybe you should try to do one single loop for 1) reading dataframe, 2) plotting and 3) saving the plot:

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"))
}

Upvotes: 1

Related Questions