2017-12-05 8 views
2

dplyr에서 그룹화 된 데이터 프레임이 생성되었으므로 각 그룹에는 고유 한 요소 변수 조합이 반영됩니다. 내가 this 게시물과 비슷한 코드를 사용하여 다른 그룹을 음모하고 싶습니다. 그러나, 나는 다른 조합의 무리를 가지고 있기 때문에 번거 로움입니다 내 플롯의 제목에 두 개 (이상) 변수를 포함하는 방법을 알아낼 수 없습니다.dplyr 그룹화를 반영하도록 ggplot 제목을 설정하십시오.

가짜 데이터와 플로팅 코드 :

library(dplyr) 
library(ggplot2) 

spiris<-iris 
spiris$site<-as.factor(rep(c("A","B","C"))) 
spiris$year<-as.factor(rep(2012:2016)) 
spiris$treatment<-as.factor(rep(1:2)) 

g<-spiris %>% 
    group_by(site, Species) %>% 
    do(plots=ggplot(data=.) + 
     aes(x=Petal.Width)+geom_histogram()+ 
     facet_grid(treatment~year)) 
     ##Need code for title here 
g[[3]] ##view plots 

나는 "사이트"와 "종"을 모두 반영하기 위해 각 플롯의 제목이 필요합니다. 어떤 아이디어? 이 같은

답변

2

사용 split() %>% purrr::map2() 대신 group_by() %>% do() :

spiris %>% 
    split(list(.$site, .$Species)) %>% 
    purrr::map2(.y = names(.), 
     ~ ggplot(data=., aes(x=Petal.Width)) + 
      geom_histogram()+ 
      facet_grid(treatment~year) + 
      labs(title = .y)) 

enter image description here

당신은 ggtitle()로 제목을 설정해야
+0

감사 친척을 닥터 네이트. 나는 여전히 map2 주위에 내 머리를 싸려고 노력하고있어. 익숙한 dplyr 함수만큼이나 직관적이지는 않지만 프로그래머보다 더 많은 연구원이 될 수 있습니다. 건배. – laroof

+0

'map2'는 쌍으로 된 두리스트 오브젝트를 반복하도록 설계 되었기 때문에'mapply'와 매우 비슷합니다 (list1 [1]은 list2 [1]과 쌍을 이룹니다). 'map2'에서 파이프 (다음에'.'라고 함)를 통해 전달되는 분할 목록과 두 번째 목록 인 .y'와 동일한 분할 목록의 이름을 살펴 보겠습니다. [Jenny Bryan의 purrr turotial] (https://jennybc.github.io/purrr-tutorial/)은 '깨끗한'학습을 시작하기에 좋은 곳입니다. – Nate

1

:

g <- spiris %>% group_by(site, Species) %>% do(plots = ggplot(data = .) + 
    aes(x = Petal.Width) + geom_histogram() + facet_grid(treatment ~ 
    year) + ggtitle(paste(.$Species,.$site,sep=" - "))) 

enter image description here