我正在使用來自 2 個不同資料集的變數的密度創建鏡像直方圖,其結構如下:
library(ggplot2)
data(iris)
ggplot()
geom_histogram(data=iris, aes(x=Sepal.Width, y=..density..), fill='#56B4E9')
geom_histogram(data=iris, aes(x=Sepal.Length, y= -..density..), fill='#D55E00')
這創造了:

但是,我想跨多個變數對映射相同的圖,因此我設定了以下內容:
var_list <- list(x = names(iris[1:4])) #define named variables
plots <- map(.x = var_list$x[1:4], #map to names
~ {
ggplot()
geom_histogram(data=iris, aes_string(x=.x, y=..density..), fill='#56B4E9')
geom_histogram(data=iris, aes_string(x=.x, y=-..density..), fill='#D55E00')
}
)
這樣做會拋出Error in aes_string(x = .x, y = ..density..) : object '..density..' not found
我可以看到在aes_string()映射時傳遞 ..density.. 存在問題,但我無法解決它。我猜我可能需要使用map2和指定.y = ,但我無法弄清楚。
任何建議表示贊賞。
uj5u.com熱心網友回復:
由于我不知道組合學應該如何在您的示例中發揮作用,因此我只考慮了從 4 列中選擇 2 列的 6 種不同可能性。
附上例子。我曾經combn()找到 6 種組合并將結果存盤在串列中var_list。
library(ggplot2)
library(purrr)
data(iris)
# combn to get the choose(4, 2) combinations:
var_list <- combn(names(iris[1:4]), 2, simplify = F) #define named variables
var_list
#> [[1]]
#> [1] "Sepal.Length" "Sepal.Width"
#>
#> [[2]]
#> [1] "Sepal.Length" "Petal.Length"
#>
#> [[3]]
#> [1] "Sepal.Length" "Petal.Width"
#>
#> [[4]]
#> [1] "Sepal.Width" "Petal.Length"
#>
#> [[5]]
#> [1] "Sepal.Width" "Petal.Width"
#>
#> [[6]]
#> [1] "Petal.Length" "Petal.Width"
## Version with aes_string():
plots <- map(var_list, #map to names
~ {
ggplot()
geom_histogram(data=iris, aes_string(x= .x[1], y = "..density.."), fill='#56B4E9')
geom_histogram(data=iris, aes_string(x= .x[2], y = "-..density.."), fill='#D55E00')
}
)
## Better using aes(), see comment:
plots2 <- map(var_list, #map to names
~ {
ggplot()
geom_histogram(data=iris, aes(x = .data[[.x[1]]], y = ..density..), fill='#56B4E9')
geom_histogram(data=iris, aes(x = .data[[.x[2]]], y = -..density..), fill='#D55E00')
}
)
由reprex 包于 2022-05-09 創建(v2.0.1)
也許這就是你要找的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/471559.html
