2017-02-08 99 views
2

我試圖用2列分隔的rmarkdown繪製任意數量的條形圖。在我的例子將有共20個地塊,所以我希望得到10個地塊中的每一列,不過,我似乎無法得到這個與grid.arrange任意數量的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我m到處以下的輸出:

enter image description here

我希望我會得到沿着線的東西:

enter image description here

但即使這樣的數字大小仍然時髦,我試圖玩heightswidths但仍然沒有運氣。道歉,如果這是一個長期的問題

+0

檢查了這一點:http://www.cookbook-r.com/Graphs/Multiple_graphs_on_one_page_(ggplot2)/ – GarAust89

+3

'grid.arrange(grobs = lapply(1:20,函數( i)ggplot()),ncol = 2)'應該可以工作,但是您需要調整設備的大小以清楚地看到圖表和傳說 – baptiste

+1

'do.call(grid.arrange,c(ggcluster,list(ncol = 2)) )'這對我有用,ggcluster是一個ggplot對象列表。任何循環交互中,列表中ggplot元素的數目都不相同 – pacomet

回答

0

如果你有一個列表中的所有ggplot對象,那麼你可以很容易地通過gridExtra::grid.arrange構建兩列圖形。這是一個簡單的例子,它將8個圖形放入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) 

enter image description here