1
votes

I'm trying to loop many plots using ggplot2 and purrr::map() combined with split(). I can get the plots working fine, but I'm having trouble extracting the split value to use as a title.

Token data:

y=tibble(SplitVar=rep(c('A','B','C'),3),
         Variable=c(rep('A',3),rep('B',3),rep('C',3)),
         Value=runif(n=9))

The plots I want are generated by:

y%>%split(y$SplitVar)%>%map(~ggplot(.,aes(Variable,Value,fill=Variable))+
                             geom_col(position='dodge'))

Sample Output Plot

but I can't figure out how to get the SplitVar values 'A','B','C' extracted to be used as:

...+labs(title=...)

I can extract the values directly:

y%>%split(y$SplitVar)%>%names(.)
[1] "A" "B" "C"

but when I try to add this to the plots,

y%>%split(y$SplitVar)%>%map(~ggplot(.,aes(Variable,Value,fill=Variable))+
                            geom_col(position='dodge')+
                            labs(title=names(.)))

I get: with the name of the variable, rather than the values.

EDIT: My data values for A are actually nested for a second split value. I can now get the labels I need, but I can't get a map function to step into the nested loop for the first value and generate plots, then step back out for the other factors. A revised input is below:

y=tibble(Split1=c(rep('A',9),rep('B',3),rep('C',3)),
   Split2=c(rep(c('A','B','C'),3),rep('D',3),rep('E',3)),
   Var=c(rep('A',3),rep('B',3),rep('C',3),rep(c('A','B','C'),2)),
   Value=runif(15)
   )

I can split the tibble into the appropriate nested list with:

y%>%split(y$Split1)%>%map(~if(.$Split1=='A') split(.,.$Split2,drop=TRUE) else .)

But the best I can come up with is separately defining two procedures:

y[[1]]%>%map(~ggplot(.,aes(Variable,Value,fill=Variable))+
             geom_col(position='dodge')+
             labs(title=unique(.x$Split2)))

y2=y%>%filter(Split1!='A')
y2%>%split(y2$Split1,drop=TRUE)%>%map(~ggplot...)
2

2 Answers

2
votes

This worked for me:

y %>%
   split(y$SplitVar) %>%
    map(~ggplot(.,aes(Variable,Value,fill=Variable))+
                        geom_col(position='dodge')+
                        labs(title=unique(.x$SplitVar)))
0
votes

Maybe this will do:

y %>%
  split(y$SplitVar) %>%
  map2(
    names(.),
    ~ ggplot(.x,aes(Variable,Value,fill=Variable))+
      geom_col(position='dodge')+
      labs(title= .y))