Home > Software engineering >  ggplot. mirrored histogram. map function include ..density
ggplot. mirrored histogram. map function include ..density

Time:05-10

I am creating a mirrored histogram using densities from variables drawn from 2 different datasets structured as follows:

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

Which creates:
enter image description here

However, I would like to map the same plot across multiple variable pairs and so I setup the following:

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

Doing so throws Error in aes_string(x = .x, y = ..density..) : object '..density..' not found

I can see that there is a problem passing ..density.. in aes_string() when mapped but I cannot resolve it. I am guessing I may need to use map2 and specify .y = but I cannot figure it out.

Any advice appreciated.

CodePudding user response:

Since I don't know how combinatorics should play a role in your example, I just took into account the 6 different possibilities to select 2 different columns out of 4.

Attached the example. I've used combn() to find the 6 combinations and stored the result in the list 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')
             }
)

Created on 2022-05-09 by the reprex package (v2.0.1)

Maybe this is what you were looking for.

  • Related