I'm trying to generate multiple plots with ggmosaic using a for loop (or map) but I'm not able to pull out the correct title names or x-axis names.
This is example of the dataframe:
set.seed(42) ## for sake of reproducibility
n <- 10
dat <- data.frame(balance=factor(paste("DM", 1:n)),
credit_history=sample(c("repaid", "critical"), 10, replace = TRUE),
purpose=sample(c("yes", "no"), 10, replace = TRUE),
employment_rate=sample(c("0-1 yrs", "1-4 yrs", ">4 yrs"), 10, replace = TRUE),
personal_status=sample(c("married", "single"), 10, replace=TRUE),
other_debtors=sample(c("guarantor", "none"), 10, replace= TRUE),
default=sample(c("yes", "no"), 10, replace = TRUE))
library(ggmosaic)
# create a list of variables
c_names <- dat[ , c("balance", "credit_history", "purpose", "employment_rate",
"personal_status", "other_debtors", "default")]
for ( col in c_names ) {
s<- ggplot(data = dat)
geom_mosaic(aes(x=product(default, col), fill = default))
ggtitle(paste("DEFAULT", col, sep = " "))
print(s)
}
Can someone give some advice?
CodePudding user response:
This is probably how I would do it. Normally if you're trying to pass strings to ggplot aesthetics, you would use aes_string()
and then pass all the aesthetic arguments as string values rather than as unquoted values. However, this doesn't seem to work with the product()
function. The alternative I proposed below is to create a temporary data object each time where the variable on the x-axis is always x
and then everything works. The title can incorporate the string without a problem.
c_names <- dat[ , c("balance", "credit_history", "purpose", "employment_rate",
"personal_status", "other_debtors", "default")]
for ( cn in colnames(c_names)[1:6]) {
tmp <- data.frame(
default =dat$default,
x = dat[[cn]]
)
s<- ggplot(data = tmp)
geom_mosaic(aes(x=product(default, x), fill = default))
ggtitle(paste("DEFAULT", cn, sep = " "))
print(s)
}
CodePudding user response:
Here is a solution slightly different from that of @DaveArmstrong.
c_names <- c("balance", "credit_history", "purpose", "employment_rate",
"personal_status", "other_debtors")
for ( col in c_names ) {
df <- dat[, c(col, "default")]
names(df)[1] <- "y"
s <- ggplot(data = df)
geom_mosaic(aes(x=product(default, y), fill = default))
ggtitle(paste("DEFAULT", col, sep = " "))
labs(x=col)
dev.new()
print(s)
}