简体   繁体   English

facet_wrap按列填充

[英]facet_wrap fill by column

As far as I can tell facet_wrap fills by row. 据我所知, facet_wrap按行填充。 In the same way you can specify how to fill a matrix with byrow I was hoping you could do the same with facet_wrap. 以同样的方式你可以指定如何用byrow填充matrix我希望你可以用facet_wrap做同样的事情。 I know I could reorder the levels of a factor to plot in this maner but this seems like a bit of work if there's a shorter method that I'm overlooking. 我知道我可以重新排序一个因子的水平以在这个方面绘制,但是如果有一个我忽略的更短的方法,这似乎有点工作。

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

How can we fill by column? 我们如何填写专栏?

This feature is implemented in the current development version of ggplot2 on github. 此功能在github上的ggplot2的当前开发版本中实现。 This commit implements a new parameter dir of facet_wrap , so you'd simply do 这个提交实现了facet_wrap的新参数dir ,所以你只需这样做

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

Note that this feature is currently not available in the version on CRAN. 请注意,此功能目前在CRAN上的版本中不可用。

It can be done by converting faceting variable into factor and then re-leveling it. 可以通过将分面变量转换为因子然后重新调整它来完成。 In function relevel.byrow I used matrix(..., byrow=T) for level ordering, then converted this matrix into a vector using c() function and then re-leveled factor. 在函数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)

I used plyr for convenience, you can just simply write 为方便起见,我使用了plyr ,你可以简单地写一下

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

This also works when we don't have full facet structure, but gives couple warnings. 当我们没有完整的构面结构时,这也有效,但会给出几个警告。

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)

Result with carb==3 excluded: carb==3排除的结果:

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM