Reputation: 27
I have a data set called panel
which has multiple categorical variables in interest.
I would like to write a program that will plot a mosaic plot for every pair using a for
loop.
vars
is the vector with the following names of the columns:
vars
[1] "region" "urb" "sex" "race" "grade" "dt01" "dt02" "dt03"
[9] "dt06" "dt07" "exercise" "kq7"
This is my program:
library(ggmosaic)
for (i in 1:12){
for (j in 1:12){
a <- vars[i]
b <- vars[j]
if (j > i){
m <- ggplot(data = panel)
m <- m + geom_mosaic(aes(x = product(a), fill = b))
}
print(m)
}
}
This code gives me a a plot with one big chunk.
When I write the column names manually like in the following code it works
ggplot(data = panel) +
geom_mosaic(aes(x = product(region), fill = urb))
I tries aes_string
but it didn't help.
Upvotes: 0
Views: 261
Reputation: 29075
Two suggestions for consideration.
1: Generate your pairs & use a single loop to go through them, rather than a double loop that goes through repeated combinations.
vars <- c("region", "urb", "sex", "race", "grade", "dt01",
"dt02", "dt03", "dt06", "dt07", "exercise", "kq7")
vars.pair <- combn(vars, 2, simplify = FALSE) # list of all valid pairs
> head(vars.pair)
[[1]]
[1] "region" "urb"
[[2]]
[1] "region" "sex"
[[3]]
[1] "region" "race"
[[4]]
[1] "region" "grade"
[[5]]
[1] "region" "dt01"
[[6]]
[1] "region" "dt02"
2: In aes_string()
, make sure x's aesthetic mapping evaluates to "product(variable.name)"
rather than product("variable.name")
.
for(i in seq_along(vars.pair)){
p1 <- vars.pair[[i]][1]
p2 <- vars.pair[[i]][2]
m <- ggplot(data = panel) +
geom_mosaic(aes_string(x = paste0("product(", p1, ")"),
fill = p2))
print(m)
}
Upvotes: 3