Chris
Chris

Reputation: 6372

Loops, dataframes and ggplot

I would like to display multiple plots on the same page using ggplot, and the multiplot function described here: http://www.cookbook-r.com/Graphs/Multiple_graphs_on_one_page_(ggplot2)/. My data is stored in a large dataframe with the first column corresponding to period. I want to visualize columns 2:26. My issue is reproducible using:

rawdata1 <- data.frame("Period" = 1:34, "Sample" = sample(x = c(1,2),34, replace = TRUE),"Runif" = runif(n = 34))

Intuitively, I would use the following code: (With 2:3 replaced with 2:26)

out <- NULL
for (i in 2:3){
  out[[i-1]] <- ggplot(rawdata1, aes("Period", y = value)) + geom_line(aes(x = Period, y = rawdata1[[i]])) + ggtitle(label = colnames(rawdata1)[i])
}

multiplot(plotlist = out, cols = 2)

This succeeds in plotting multiple graphs, however my problem is that each graph that is plotted uses data from the same column (column 3 in the above example, column 26 in my dataset). I've puzzled out that this is because my "out" list stores the ggplot list with the y values stored dynamically.

i's final value is 26, and when I call an item from "out", it uses the current value for i to create the graph. So every graph displays using the same column. As I am new to R, so my guess is that I am not managing my variables correctly. Any help would be appreciated

Upvotes: 0

Views: 423

Answers (1)

shadow
shadow

Reputation: 22293

Below you find an alternative: using the melt function from reshape2 and then faceting with facet_wrap.

require(ggplot2)
require(reshape2)
data.melt <- melt(rawdata1, id.var='Period')
ggplot(data.melt, aes(Period, value)) + 
  geom_line() + 
  facet_wrap(~variable, scales='free_y')

If you want to use multiplot instead, you could do the following:

out <- lapply(names(rawdata1)[-1], 
               function(index) ggplot(rawdata1) + 
                 geom_line(aes_string(x = 'Period', y = index)) + 
                 ggtitle(label = index))
multiplot(plotlist = out, cols = 2)

Upvotes: 1

Related Questions