我正在尝试使用for循环(或map)生成多个带ggmosaic的图形,但我无法提取正确的标题名或x轴名称。
这是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)
}有人能给我点建议吗?
发布于 2021-12-06 16:18:27
我可能就是这样做的。通常,如果您试图将字符串传递给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-06 16:30:58
这是一个与@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)
}https://stackoverflow.com/questions/70248200
复制相似问题