2012-10-15 131 views
11

據我可以告訴facet_wrap逐行填寫。以同樣的方式,你可以指定如何填寫matrixbyrow我希望你可以用facet_wrap做同樣的事情。我知道我可以重新排列一個因素的水平,以便在這個方面進行繪圖,但是如果我忽略了一個更短的方法,這看起來像是一些工作。facet_wrap填充列

library(ggplot2) 

ggplot(mtcars, aes(x=gear, y=mpg, fill=vs)) + 
    geom_bar(position="dodge", stat="identity") + 
    facet_wrap(~ carb, ncol=2) #fills by row 

我們如何按欄填寫?

+0

好問題。在'ggplot2' [回購](https://github.com/hadley/ggplot2/issues?labels=feature&page=1&state=open)上將它作爲Winston的功能請求發佈。 :) – Maiasaura

+0

完成:https://github.com/hadley/ggplot2/issues/695 –

+0

雖然也許我在錯誤的地方添加了請求,因爲鏈接與您的鏈接不匹配。 –

回答

4

它可以通過將分面變量轉換爲因子然後重新對其進行重新平衡來完成。在函數relevel.byrow中,我使用matrix(..., byrow=T)進行級別排序,然後使用c()函數將此矩陣轉換爲矢量,然後重新校準因子。

#number of columns 
nc <- 2 
level.byrow <- function(vec, nc){ 
    fac <- factor(vec) #if it is not a factor 
    mlev <- matrix(levels(fac), nrow=nc, byrow=T) 
    factor(fac, levels= c(mlev)) 
} 

library(plyr) 
ggplot(transform(mtcars, rcarb=level.byrow(carb, nc)), aes(x=gear, y=mpg, fill=vs)) + 
    geom_bar(position="dodge", stat="identity") + 
    facet_wrap(~ rcarb, ncol=nc) 

我用plyr爲了方便,你可以簡單地寫

mtcars$rcarb <- level.byrow(mtcars$carb, nc) 

這也適用,當我們沒有完全小面結構,但給出了一些警告。

mtcars2 <- subset(mtcars, carb!=3) 
ggplot(transform(mtcars2, rcarb=level.byrow(carb, nc)), aes(x=gear, y=mpg, fill=vs)) + 
    geom_bar(position="dodge", stat="identity") + 
    facet_wrap(~ rcarb, ncol=nc) 

結果與carb==3排除:

enter image description here

+0

聽起來像by列選項不適用於facet_wrap。此解決方案遭受重新排列的級別,因此應該創建一個新的變量來保存原始數據。不理想,但我認爲現在最好的工作。謝謝你的想法。 –

4

該功能在GitHub上GGPLOT2的當前的開發版本中實現。 This commit實現了新的參數facet_wrapdir,所以你根本就

## "v" for vertical or "h" for horizontal (the default)  
ggplot(...) + facet_wrap(~ carb, ncol=2, dir="v") 

注意,此功能目前尚未在CRAN的版本。

+0

這是目前理想的解決方案,因爲易於實施。 'facet_wrap()'的'dir'參數現在是CRAN ggplot2版本的一部分。 – Megatron