【问题标题】:arbitrary number of plots for grid.arrangegrid.arrange 的任意数量的图
【发布时间】:2017-02-08 21:26:43
【问题描述】:

我正在尝试绘制任意数量的条形图,其中 rmarkdown 由 2 列分隔。在我的示例中,总共将有 20 个图,所以我希望在每列中获得 10 个图,但是,我似乎无法使用 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)

当我将它编织成 html 时,我得到以下输出:

我希望我能得到类似的东西:

但即便如此,人物尺寸仍然很时髦,我尝试过使用heightswidths,但仍然没有运气。抱歉,如果这是一个很长的问题

【问题讨论】:

  • grid.arrange(grobs=lapply(1:20, function(i) ggplot() ), ncol=2) 应该可以工作,但您需要调整设备大小才能清楚地看到图表和图例
  • do.call(grid.arrange, c(ggcluster,list(ncol=2))) 这对我有用,因为 ggcluster 是一个 ggplot 对象的列表。列表中 ggplot 元素的数量在任何循环交互中都不同

标签: r plot ggplot2 knitr do.call


【解决方案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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-15
    • 1970-01-01
    • 2012-03-18
    相关资源
    最近更新 更多