laoisman
laoisman

Reputation: 61

How to plot with minimum no. of observations using facet_wrap, ggplot2

Have searched for the answer to this but cannot find anything relevant.

I am plotting a dataframe using ggplot2 and facet_wrap to get multiple plots, which is working fine. The idea is to quickly look for trends in the x, y relationship.

However, at some levels, there are few data points, so identifying a trend is not possible and the individual plot does not fulfill any role.

My question is: is it possible to pre-define a minimum number of observations before facet_wrap will plot? Or do I have to re-format my dataframe to remove subsets where the number of observations within a level is limited.

Hope this makes sense, thanks in advance.

Upvotes: 0

Views: 360

Answers (1)

glaucon
glaucon

Reputation: 238

Here is an answer to your question:

library(tidyverse)

set.seed(567)

# create dummy data frame with 4 types in column x, 
# one of which, "d", only has 2 observations

my.df <- tibble(x = c(rep(c("a", "b", "c"), 25), rep("d", 2)),
                y = rnorm(78))

# when faceted, "d" lacks sufficient data

my.df %>% 
  ggplot(aes(y)) +
  geom_histogram(binwidth = 0.5) +
  facet_wrap(~ x)

enter image description here

# use the add_count function to solve your problem when faceting

my.df %>% 
  add_count(x) %>% 
  filter(n > 10) %>% 
  ggplot(aes(y)) +
  geom_histogram(binwidth = 0.5) +
  facet_wrap(~ x)

enter image description here

Upvotes: 1

Related Questions