ggplot2:facet_wrap中的控制面板位置

时间:2018-04-17 17:03:22

标签: r ggplot2 facet-wrap facet-grid

我有一个嵌套因子的数据集,类似于嵌套在mpg model的{​​{1}}数据集:

manufacturer

如果我按mpgsub <- subset(mpg, manufacturer %in% c("audi", "dodge","jeep","subaru")) mpgsub$model <- as.factor(mpgsub$model) table(mpgsub$manufacturer, mpgsub$model) facet_grid使用manufacterer,我会看到空面板:

model

enter image description here

我想制作一个按模型划分的ggplot,但是按制造商排列面板。

我用ggplot(mpgsub, aes(cty, hwy)) + geom_point() + facet_grid(manufacturer~model) 尝试了这个。我知道如果我改变facet_wrap因子级别的顺序,我可以控制面板顺序,但它仍然只是在不考虑model

manufacturer

enter image description here

理想情况下,我会让制造商按行排列面板,即使这意味着不同的行长度,因为在我的子集中每个制造商都有不同数量的模型。我将下面的图片安排在图形软件中 - 有没有办法让ggplot2这样做? enter image description here

我知道我可以通过#order models by manufacturer levels(mpgsub$model) mpgsub$model <- factor(mpgsub$model, levels=c( "a4", "a4 quattro","a6 quattro" , #Audi "caravan 2wd", "dakota pickup 4wd", "durango 4wd", "ram 1500 pickup 4wd", #Dodge "grand cherokee 4wd", #Jeep "forester awd","impreza awd" )) #Subaru ggplot(mpgsub, aes(cty, hwy)) + geom_point()+ facet_wrap(~model, nrow=4, ncol=4) here下讨论的scales=FREE参数来控制这样的事情,但它似乎只适用于x或y轴,我想要为不同的变量保留y轴。

1 个答案:

答案 0 :(得分:0)

也许这足以让你走上正轨?主要贡献是ggpubr包中的library(dplyr) library(ggplot2) library(ggpubr) mpgsub <- subset(mpg, manufacturer %in% c("audi", "dodge","jeep","subaru")) mpgsub$model <- as.factor(mpgsub$model) mpgsub1 = mpgsub %>% filter(manufacturer == "audi") mpgsub2 = mpgsub %>% filter(manufacturer == "dodge") plot1 = ggplot(mpgsub1, aes(cty, hwy)) + geom_point() + facet_grid(~model) + labs(title = "audi") plot2 = ggplot(mpgsub2, aes(cty, hwy)) + geom_point() + facet_grid(~model) + labs(title = "dodge") plot3 = ggarrange(plot1,plot2, nrow = 2) print(plot3) 方法。

host.docker.internal

enter image description here