Ted Mosby Ted Mosby - 5 months ago 33
R Question

plot each row in a data.frame in a list using ggplot

I have a list of data.frames and I want to plot each row of each data.frame using ggplot. I'm looking to store these into a variable so then I can plot these in a png in a 20x12 format. Meaning 20 graphs across and 12 down.

Each data.frame in the list would get it's own png file.

df = data.frame(matrix(rnorm(n=240), nrow = 240, ncol = 602))
df_list = list(df,df,df)
for (i in 1:length(df_list)){
for (k in 1:240){
testdf = as.numeric(t(df[[i]][k,2:ncol(df[[i]])]))
testtime = seq_along(df[[i]])
test =((cbind(testtime,testdf)))
test = as.data.frame(test)

The following code gets me the last loop of [i] but it doesnt save the first few loops. Any ideas?

Bonus Points if you know how to plot each [i] into separate png files in a matrix of plots measuring 20x12.


If you are willing to tidy your data, you can use this, which will automatically generate the 20x12 layout for each of the data.frames:


df = data.frame(matrix(rnorm(n=240), nrow = 240, ncol = 602)) %>%
  mutate(id = 1:nrow(.)) %>%
  gather(index, value, -id) %>%
  mutate(index = parse_number(index))

df_list = list(df,df,df)

catch <- lapply(df_list, function(df){
         , aes(x = index
               , y = value)) +
    geom_line() +
               , nrow = 20
               , ncol = 12) +
    theme(strip.text = element_blank())

One of the plots:

enter image description here

Note that you will want to make thematic changes, particularly if you want to be able to label the individuals, but this at least generates the layout you wanted.