ggplot2和purrr:使用split()循环并引用索引值 [英] ggplot2 and purrr: loop with split() and refer to index value
问题描述
我正在尝试使用ggplot2和purrr :: map()结合split()循环许多图.我可以使绘图工作正常,但是在提取分割值以用作标题时遇到了麻烦.
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.
令牌数据:
y=tibble(SplitVar=rep(c('A','B','C'),3),
Variable=c(rep('A',3),rep('B',3),rep('C',3)),
Value=runif(n=9))
我想要的地块由生成:
y%>%split(y$SplitVar)%>%map(~ggplot(.,aes(Variable,Value,fill=Variable))+
geom_col(position='dodge'))
但是我不知道如何获取将SplitVar值'A','B','C'提取来用作:
but I can't figure out how to get the SplitVar values 'A','B','C' extracted to be used as:
...+labs(title=...)
我可以直接提取值:
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(.)))
我得到:加上变量的名称,而不是 values .
I get: with the name of the variable, rather than the values.
我的A数据值实际上是为第二个拆分值嵌套的.现在,我可以获取所需的标签,但是无法获取映射函数以进入嵌套循环以获取第一个值并生成图,然后退出以获取其他因素.修改后的输入如下:
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...)
推荐答案
这对我有用:
y %>%
split(y$SplitVar) %>%
map(~ggplot(.,aes(Variable,Value,fill=Variable))+
geom_col(position='dodge')+
labs(title=unique(.x$SplitVar)))
这篇关于ggplot2和purrr:使用split()循环并引用索引值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!