Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a collection of plots inside of a `for` loop

Tags:

r

ggplot2

I have 15 plots that I need to display, which I iterate through in a for list like so:

### Plotting that does not work
plots <- c()
for (i in colnames(dataframeselect)){
  current_col <- dataframeselect[i]
  plots <- c(plots, ggplot(dataframeselect, aes_string(colnames(current_col))) + geom_histogram())
}
ggarrange(plotlist = plots)

While I can iterate and create plots individually I can't manage to create a plot list, that I can then pass to ggarrange.

I now have to resort to create 15 variables, which gets the job done fine but is somewhat tedious and not DRY-friendly:

### Plotting that works
my_plot <- function(column) ggplot(dataframeselect, aes_string(x = column)) + geom_histogram()

p1 <- my_plot("W3_f15771g")
p2 <- my_plot("W3_f15771a")
p3 <- my_plot("W3_f15771b")
#...
ggarrange(p1,p2,p3)

Please note that there is a question already being asked, but none of those answers use a for loop in order to get the desired result: Lay out multiple ggplot graphs on a page

The warning that I get is the following:

  Cannot convert object of class FacetNullFacetggprotogg into a grob.
44: In as_grob.default(plot) :
  Cannot convert object of class environment into a grob.
45: In as_grob.default(plot) : Cannot convert object of class list into a grob.
46: In as_grob.default(plot) :
  Cannot convert object of class tbl_dftbldata.frame into a grob.
47: In as_grob.default(plot) : Cannot convert object of class list into a grob.
48: In as_grob.default(plot) :
  Cannot convert object of class ScalesListggprotogg into a grob.
49: In as_grob.default(plot) : Cannot convert object of class uneval into a grob.
50: In as_grob.default(plot) : Cannot convert object of class list into a grob.

What is interesting is that, whenever I add a new plot to my list, the count of the objects does not increment by 1 but by nine elements. So by looking at the plots variable, I see that it is a big mess not of some plot objects but of all the fragments from all the plots I wanted to add:

messed-up-data-soup

So I am wondering how to somehow put the plot inside some sub-container that it then can be used by ggarrange.

like image 741
Besi Avatar asked Oct 29 '25 16:10

Besi


1 Answers

One option is to initialize the plots as a list with length same as the number of columns of dataset

library(ggplot2)
plots <-  vector('list', ncol(dataframeselect))
for (i in seq_along(dataframeselect)){
  current_col <- colnames(dataframeselect)[i]
  plots[[i]] <- ggplot(dataframeselect, aes_string(current_col)) + 
                                      geom_histogram()
 }
like image 80
akrun Avatar answered Nov 01 '25 05:11

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!