r - How to map tibble elements to ggplot2 aesthetics? -
i have following dataset
map(.x = list(small = 3, medium = 10, large = 100) , .f = ~ sample(rnorm(1000), .x, replace = t)) %>% tibble(sample = ., mean = map_dbl(., mean)) # tibble: 3 x 2 sample mean <list> <dbl> 1 <dbl [3]> 0.61473548 2 <dbl [10]> 0.17278357 3 <dbl [100]> 0.04156308
i trying functionally create 1 histogram in ggplot2 each record in column sample
. display plots in same grid, thought somehow use facet_wrap()
not sure how map aesthetics lists.
this have tried far:
map(.x = list(small = 3, medium = 10, large = 100) , .f = ~ sample(rnorm(1000), .x, replace = t)) %>% tibble(sample = ., mean = map_dbl(., mean)) %>% ggplot2::ggplot(data = .) + geom_histogram(mapping = aes(sample)) + facet_wrap(~ sample)
the output expect 3 histograms 3, 10 , 100 observations respectively.
i wonder if possible solution involve splitting sample
in 2 columns: 1 values, indicating distribution size each value belongs to. more compliant ggplot2 logic, not sure how expand tibble accordingly.
ps: not sure how phrase question suggestions welcome
i think need tidyr::unnest
:
library(dplyr) library(tidyr) library(ggplot2) ## generate data set.seed(123) dtf <- map(.x = list(small = 3, medium = 10, large = 100), .f = ~ sample(rnorm(1000), .x, replace = t)) %>% tibble(sample = ., mean = map_dbl(., mean)) ## plot dtf %>% mutate(group = names(sample)) %>% # or: group = lengths(sample) unnest(sample) %>% ggplot(data = .) + geom_histogram(mapping = aes(sample)) + facet_wrap(~ group)
wiki
Comments
Post a Comment