使用 ggplot2 在构面中删除未使用的级别

机器算法验证 r 数据可视化 ggplot2
2022-02-12 07:19:20

是否可以删除 ggplot2s 方面未使用的级别?这是我的代码:

tab = as.data.frame(cbind(groups = mtcars$cyl, names = row.names(mtcars), val = mtcars$mpg, N = mtcars$disp))
tab$N = as.numeric(tab$N)

ggplot(tab, aes(names,val)) + 
geom_point() + coord_flip() + 
theme_bw() + 
facet_grid(groups ~ ., drop=TRUE)#, scales="free", as.table=F, space="free")

我尝试了drop=T开关,但它没有帮助。我究竟做错了什么?

1个回答

您的示例数据没有任何未使用的级别可以删除。检查此示例中的行为:

dat <- data.frame(x = runif(12),
                  y = runif(12),
                  grp1 = factor(rep(letters[1:4],times = 3)),
                  grp2 = factor(rep(LETTERS[1:2],times = 6)))

levels(dat$grp2) <- LETTERS[1:3]

ggplot(dat,aes(x = x,y = y)) + 
    facet_grid(grp1~grp2,drop = FALSE) + 
    geom_point()

ggplot(dat,aes(x = x,y = y)) + 
    facet_grid(grp1~grp2,drop = TRUE) + 
    geom_point()

您可能希望更改在每个方面的垂直轴上绘制的因素,在这种情况下,您希望设置scales参数并使用facet_wrap

ggplot(tab, aes(names,val)) + 
    geom_point() + coord_flip() + 
    theme_bw() + 
    facet_wrap(~groups,nrow = 3,scales = "free_x")