2

I'm trying to plot an arbitrary number of bar plots with rmarkdown separated by 2 columns. In my example there will be 20 total plots so I was hoping to get 10 plots in each column, however, I can't seem to get this to work with grid.arrange

plot.categoric = function(df, feature){
  df = data.frame(x=df[,feature])
  plot.feature = ggplot(df, aes(x=x, fill = x)) + 
    geom_bar() +
    geom_text(aes(label=scales::percent(..count../1460)), stat='count', vjust=-.4) +
    labs(x=feature, fill=feature) +
    ggtitle(paste0(length(df$x))) +
    theme_minimal()
  return(plot.feature)
}


plist = list()
for (i in 1:20){
  plist = c(plist, list(plot.categoric(train, cat_features[i])))
}

args.list = c(plist, list(ncol=2))
do.call("grid.arrange", args.list)

When I knit this to html I'm getting the following output:

enter image description here

I was hoping I would get something along the lines of:

enter image description here

but even with this the figure sizes are still funky, I've tried playing with heights and widths but still no luck. Apologies if this is a long question

4

1 回答 1

1

如果您有ggplot一个列表中的所有对象,那么您可以通过 轻松构建两列图形gridExtra::grid.arrange。这是一个简单的例子,它将八个图形放入一个 4x2 矩阵中。

library(ggplot2)
library(gridExtra)

# Build a set of plots
plots <-
  lapply(unique(diamonds$clarity),
         function(cl) {
           ggplot(subset(diamonds, clarity %in% cl)) +
           aes(x = carat, y = price, color = color) +
           geom_point()
         })

length(plots)
# [1] 8

grid.arrange(grobs = plots, ncol = 2)

在此处输入图像描述

于 2017-05-31T06:46:03.653 回答