Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to exclude facet wrap/grid with less than n number of observations in R

I am using ggplot to create numerous dot charts (using geom_point and facet_wrap) for two variables with multiple categories. Multiple categories have only a few points, which I cannot use,

Is there a way to set a minimum number of observations for each facet (i.e. only show plots with 10 or more observations)?

by_AB <- group_by(df, A, B)

by_AB%>% 
  ggplot(aes(X,Y)) +
  geom_point() +
  facet_wrap(A~B,  scales="free") + 
  geom_smooth(se = FALSE) +
  theme_bw()``` 

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It is best to remove the small groups from your data before plotting. This is very easy if you do

df %>% 
  group_by(A, B) %>% 
  filter(n() > 1) %>%
  ggplot(aes(X,Y)) +
  geom_point() +
  facet_wrap(A~B,  scales="free") + 
  geom_smooth(se = FALSE) +
  theme_bw()

Obviously, we don’t have your data, so here is an example using the built-in mtcars data set. Suppose we want to plot mpg against wt, but facet by carb:

library(tidyverse)

mtcars %>%
  ggplot(aes(wt, mpg)) +
  geom_point() +
  facet_wrap(.~carb)

Two of our facets look out of place because they only have a single point. We can simply filter these groups out en route to ggplot:


mtcars %>%
  group_by(carb) %>%
  filter(n() > 1) %>%
  ggplot(aes(wt, mpg)) +
  geom_point() +
  facet_wrap(.~carb)

Created on 2022-08-25 with reprex v2.0.2

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading