ggmosaic 未在标题或 x-axis 中显示正确的列名称

ggmosaic doesn't display the correct column names in title or x-axis

我正在尝试使用 for 循环(或地图)使用 ggmosaic 生成多个图,但我无法提取正确的标题名称或 x-axis 名称。

这是数据框的示例:

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)
  }

有人可以给点建议吗?

我可能会这样做。通常,如果您尝试将字符串传递给 ggplot 美学,您将使用 aes_string() 然后将所有美学参数作为字符串值而不是不带引号的值传递。但是,这似乎不适用于 product() 函数。我在下面提出的替代方案是每次创建一个临时数据 object,其中 x-axis 上的变量始终是 x,然后一切正常。标题可以合并字符串没有问题。

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)
}

这是一个与@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)
}