本文介绍了facet_wrap按列填充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 据我可以告诉 facet_wrap 逐行填写。以同样的方式,你可以指定如何用 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)#b 我们如何填写列?解决方案可以通过将分面变量转换为因子并重新平衡它来完成。在函数 relevel.byrow 中,我使用了矩阵(...,byrow = T)矩阵转换为一个使用 c()函数的向量,然后重新校准因子。 $ c>#列数 nc level.byrow fac mlev 因子(fac,levels = c(mlev))} 库(plyr) ggplot(变换(mtcars,rcarb = level.byrow(carb,nc)),aes(x =齿轮,y = mpg,fill = vs))+ geom_bar (position =dodge,stat =identity)+ facet_wrap(〜rcarb,ncol = nc) 为方便起见,我使用了 plyr ,您可以简单地写下 mtcars $ rcarb mtcars2 子集(mtcars,carb!= 3) ggplot(变换(mtcars2,rcarb = level.byrow(carb,nc)),aes(x =齿轮,y = mpg,fill = vs))+ geom_bar(position =dodge,stat =identity)+ facet_wrap(〜rcarb,ncol = nc) 不包括 carb == 3 的结果: As far as I can tell facet_wrap fills by row. 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. 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 rowHow can we fill by column? 解决方案 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.#number of columnsnc <- 2level.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 writemtcars$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: 这篇关于facet_wrap按列填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 07-01 23:07