0

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

这是数据框的示例:

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

有人可以给点建议吗?

4

2 回答 2

2

这可能是我会做的。通常,如果您尝试将字符串传递给 ggplot 美学,您将使用aes_string()然后将所有美学参数作为字符串值而不是作为未引用的值传递。但是,这似乎不适用于该product()功能。我在下面提出的替代方案是每次创建一个临时数据对象,其中 x 轴上的变量始终是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)
}

于 2021-12-06T16:18:27.600 回答
2

这是一个与@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)
}
于 2021-12-06T16:30:58.567 回答