使用函数在 R 中创建用于可视化的箱线图

Creating boxplots for visualisation in R using a function

我写了一个代码来获取箱线图以在 R 中进行可视化。代码是 运行 但我没有得到任何箱线图。你能帮我找出我错在哪里吗?

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)

代码没问题,只是当你在一个函数中调用 ggplot 时,你 return 对象并且它存储在一个列表中。你需要打印它。例如:

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)

这显示了 y_var[1]

的情节
month_box[[1]]
#or print(month_box[[1]])

要在 1 个地块中获取所有内容,请执行以下操作:

grid.arrange(grobs=month_box)