facet_limits: Custom facet limits

Description Usage Arguments Examples

View source: R/ggplots.R

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

1
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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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. 13, 2018, 7:05 a.m.