facet_limits: Custom facet limits

View source: R/ggplots.R

facet_limitsR Documentation

Custom facet limits

Description

Modify x-axis limits for facet_wrap.

When melting a data set of factor variables, the desired levels are dropped during the reshaping to a single variable. Therefore, variables will either show all unique values as levels or only levels where data is present. This function gives ability to set custom x limits for each variable (including the side effect of working for continuous variables).

Usage

facet_limits(pl, limits, useNA = c("ifany", "no", "always"))

Arguments

pl

a ggplot object

limits

a named list containing one for more limits for each subplot

useNA

how to handle NA values

Examples

library('ggplot2')
datf <- datn <- mtcars[, c(2, 8:11)]
datf[] <- lapply(datf, factor)

datfl <- reshape2::melt(datf, id.vars = 'am')
datnl <- reshape2::melt(datn, id.vars = 'am')

datfl$value[datfl$value == 4] <- NA
# datfl <- na.omit(datfl)

pf <- ggplot(datfl, aes(value, fill = factor(am))) +
  # facet_wrap(~ variable) +
  facet_wrap(~ variable, scales = 'free') +
  geom_bar(position = 'dodge')

## facets either show all levels for each plot or only those with data
pf

facet_limits(pf, list(gear = c(3,4,5), vs = 0:6), useNA = 'no')

facet_limits(pf, lapply(datf, levels), useNA = 'no')
facet_limits(pf, lapply(datf, levels), useNA = 'ifany')
facet_limits(pf, lapply(datf, levels), useNA = 'always')

pn <- ggplot(datnl, aes(value, fill = factor(am))) +
  facet_wrap(~ variable, scales = 'free_x') +
  geom_bar(position = 'dodge')
pn

facet_limits(pn, list(carb = c(0,100)))

facet_limits(pn, lapply(datn, extendrange, f = 1))
facet_limits(pn, list(c(0,10), c(-1,5), c(2,8), c(0,20)))


raredd/plotr documentation built on Nov. 19, 2023, 4:09 a.m.