我正在嘗試使用 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)
}
有人可以給一些建議嗎?
uj5u.com熱心網友回復:
這可能是我要做的。通常,如果您嘗試將字串傳遞給 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)
}
uj5u.com熱心網友回復:
這是一個與@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://www.uj5u.com/qiye/375188.html
上一篇:條形圖中的合計百分比
下一篇:根據另一列更改具有多個值的列
