0

I wrote a code to get boxplots for visualisation in R. The code is running but I am not getting any boxplots. Can you please help identify where I went wrong.

create_boxplots <- function(x, y){
  ggplot(data = forest_fires) +
  aes_string(x = x, y = y) +
  geom_boxplot() +
  theme(panel.background = element_rect(fill = "white"))
}

    x_var_month <- names(forest_fires)[3]
    y_var <- names(forest_fires)[5:12]
    month_box <- map2(x_var_month, y_var, create_boxplots)
StupidWolf
  • 45,075
  • 17
  • 40
  • 72
Robin0105
  • 31
  • 6
  • 1
    Welcome to stackoverflow. Try to remove unnecessary variables, and create a reproducible error with simplest code possible so that others can try and replicate the same error, and help you. All the best. – tired and bored dev Mar 05 '20 at 11:29
  • To add to the above, it would be even better if you could include a [reproducible data example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) to go along with that [reproducibly code example](https://stackoverflow.com/help/minimal-reproducible-example). – David Buck Mar 05 '20 at 11:46

1 Answers1

1

The code is ok, just that when you call ggplot inside a function, you return the object and it is stored in a list. You need to print it. For example:

library(ggplot2)
library(purrr)
library(gridExtra)

create_boxplots <- function(x, y){
  ggplot(data = forest_fires) +
  aes_string(x = x, y = y) +
  geom_boxplot() +
  theme(panel.background = element_rect(fill = "white"))
}

forest_fires = data.frame(matrix(runif(1300),ncol=13))
forest_fires[,3] = factor(sample(1:12,nrow(forest_fires),replace=TRUE))

    x_var_month <- names(forest_fires)[3]
    y_var <- names(forest_fires)[5:12]
    month_box <- map2(x_var_month, y_var, create_boxplots)

This shows you the plot for y_var[1]

month_box[[1]]
#or print(month_box[[1]])

enter image description here

To get everything in 1 plot do:

grid.arrange(grobs=month_box)

enter image description here

StupidWolf
  • 45,075
  • 17
  • 40
  • 72