Only keep som groups when facetting in ggplot2

2019-08-20 06:41发布

问题:

I have the following example. How can I limit the number of facets, e.g. only keep audi and dodge?

library(tidyverse)

ggplot(mpg) +
  geom_histogram(aes(displ)) +
  facet_wrap(~ manufacturer)

回答1:

A fast workaround would be subsetting your data inside the ggplot call (check the accepted answer in this link).

In your case I believe that you should add a subset(mpg,manufacturer %in% c("audi","dodge")) call inside the first ggplot argument.

Code:

> ggplot(subset(mpg,manufacturer %in% c("audi","dodge"))) +
+     geom_histogram(aes(displ)) +
+     facet_wrap(~ manufacturer)

This produces the desired output:

Edit: Both answers appeared at the same time with the same solution



回答2:

What about this, working on the dataset:

library(tidyverse)

mpg %>%
# select only desired manifacturers
filter(manufacturer %in% c('audi','dodge')) %>%  
 ggplot() +
 geom_histogram(aes(displ)) +
 facet_wrap(~ manufacturer)



标签: r ggplot2