据我所知,facet_wrap按行填写.以同样的方式,你可以指定如何填充matrix与byrow我希望你可以做同样的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
Run Code Online (Sandbox Code Playgroud)
我们如何填写专栏?
jhi*_*hin 10
此功能在github上的ggplot2的当前开发版本中实现.这个承诺实现了一个新的参数dir的facet_wrap,所以你根本就
## "v" for vertical or "h" for horizontal (the default)
ggplot(...) + facet_wrap(~ carb, ncol=2, dir="v")
Run Code Online (Sandbox Code Playgroud)
请注意,此功能目前在CRAN上的版本中不可用.
可以通过将分面变量转换为因子然后重新调整它来完成。在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)
Run Code Online (Sandbox Code Playgroud)
我plyr使用方便,你可以简单地写
mtcars$rcarb <- level.byrow(mtcars$carb, nc)
Run Code Online (Sandbox Code Playgroud)
当我们没有完整的构面结构时,这也有效,但会给出几个警告。
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)
Run Code Online (Sandbox Code Playgroud)
结果carb==3排除:
