Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting foreach() and ggplot2 to get along

Tags:

foreach

r

ggplot2

I have a set of survey data, and I'd like to generate plots of a particular variable, grouped by the respondent's country. The code I have written to generate the plots so far is:

countries <- isplit(drones, drones$v3)
foreach(country = countries) %dopar% {
  png(file = paste(output.exp, "/Histogram of Job Satisfaction in ", country$key[[1]], ".png", sep = ""))
  country.df <- data.frame(country)  #ggplot2 doesn't appreciate the lists nextElem() produces
  ggplot(country.df, aes(x = value.v51)) + geom_histogram()
  dev.off()
}

The truly bizarre thing? I can run the isplit(), set country <- nextElem(countries), and then run through the code without sending the foreach line - and get a lovely plot. If I send the foreach, I get some blank .png files.

I can definitely do this with standard R loops, but I'd really like to get a better grasp on foreach.

like image 814
Matt Parker Avatar asked Aug 30 '09 02:08

Matt Parker


1 Answers

You need to print the plot if you want it to display:

print(ggplot(country.df, aes(x = value.v51)) + geom_histogram())

By default, ggplot commands return a plot object but the command itself does not actually display the plot; that is done with the print command. Note that when you run code interactively, results of commands get printed which is why you often don't need the explicit print. But when wrapping in a foreach, you need to explicitly print since the results of the commands in the body will not be echoed.

like image 70
Jonathan Chang Avatar answered Oct 13 '22 20:10

Jonathan Chang