简体   繁体   中英

Plotting a collection of variables on a grid in R

I would like to learn a good way to plot a collection of variables p (dataframe columns) into a grid rather than writing out each variable into the grid.arrange function.

p <- c()
for (i in 1:length(names(df)) - 1){
  p[i] <- qplot(df[i])
}
grid.arrange(p, ncol = 5)

I want a method for: grid.arrange(p[1], p[2], ..., p[n] ) to plot each graph in a grid.

pl = replicate(5, ggplot(), simplify = FALSE)
grid.arrange(grobs = pl)

Note that your strategy could use a few improvements:

  • preallocating p would be better with p = vector(length = ncol(df)-1, mode="list")
  • p[[i]] <- not p[i] <-
  • 1:3 - 1 produces 0 1 2 , and 0 isn't a valid index
  • it's easier to work with long format data frames (tidy data) in ggplot/R; try reshape2::melt() or tidyr::gather() and alternatives, so that you can avoid an awkward loop over column names

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM