图表。镜像直方图。地图功能包括..density

ggplot. mirrored histogram. map function include ..density

我正在使用从结构如下的 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 = 但我无法弄清楚。

感谢任何建议。

因为我不知道组合学在你的例子中应该如何发挥作用,所以我只考虑了 6 种不同的可能性 select 4 列中的 2 列。

附上范例。我使用 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 package (v2.0.1)

于 2022-05-09 创建

也许这就是您要找的。