SiH
SiH

Reputation: 1546

ggplot with faceting at multiple levels

I used facet-grid to seggregate scatterplot based on categorical variables (4 levels of faceting).

  1. Can someone please show how to label each panel (e.g. a = 1) so that plot is self informative.
  2. Suggest on further improving to improve it to publishable quality.

I have attached a sample code

library(tidyverse)

# continuous variables
x <- runif(160)
y <- runif(160)

# categorical variables
a <- c(rep(0, 80), rep(1, 80))
b <- c(rep(0, 40), rep(1, 40), rep(0, 40), rep(1, 40))
c <- c(rep(0, 20), rep(1, 20), rep(0, 20), rep(1, 20), 
       rep(0, 20), rep(1, 20), rep(0, 20), rep(1, 20))
d <- c(rep(0, 10), rep(1, 10), rep(0, 10), rep(1, 10),
       rep(0, 10), rep(1, 10), rep(0, 10), rep(1, 10),
       rep(0, 10), rep(1, 10), rep(0, 10), rep(1, 10),
       rep(0, 10), rep(1, 10), rep(0, 10), rep(1, 10))

# tibble
tbl <- tibble(x, y, a, b, c, d)

# ggplot
ggplot(data = tbl,
       aes(x = x,
           y = y)) + 
  geom_point() + 
  facet_grid(a + d ~ b + c) +
  theme_bw() +
  theme(aspect.ratio = 1)

enter image description here

Upvotes: 0

Views: 529

Answers (1)

Rui Barradas
Rui Barradas

Reputation: 76402

Here is a solution with interaction followed by sub.

tbl %>%
  mutate(A = interaction(a, d, sep = "_"),
         B = interaction(b, c, sep = "_"),
         A = sub("(.)_", "a = \\1, d = ", A),
         B = sub("(.)_", "b = \\1, c = ", B)) %>%
  # ggplot
  ggplot(
    aes(x = x,
        y = y)) + 
  geom_point() + 
  facet_grid(A ~ B) +
  theme_bw() +
  theme(aspect.ratio = 1,
        axis.text.x = element_text(angle =60, vjust = 1, hjust=1))

enter image description here

Upvotes: 2

Related Questions