Reputation: 1546
I used facet-grid to seggregate scatterplot based on categorical variables (4 levels of faceting).
a = 1
) so that plot is self informative.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)
Upvotes: 0
Views: 529
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))
Upvotes: 2