2015-01-03 6 views
2

gtable을 사용하여 ggplot 개체를 조작하는 법을 배우고 있습니다. [여기서 I는 요청 관련 문제는 : dismantling a ggplot with grid and gtable]gtable 내의 ggplot 요소 바꾸기 : 레이블 및 눈금 선

본 문제이다

<올 시작 = "2"> 하나 gtable에서 다양한 축 요소를 가지고 다른 gtable에서로를 배치하는 방법
  • 기존 요소의 대체? 및 특히 : 수직 그리드 선 (및 해당 눈금)을 대체하십시오.
  • 일부 코드 및 그림 아래

    여기 enter image description here

    # replace the bottom axis of p1 with that of p2 
    library(gtable) 
    g1 <- ggplot_gtable(ggplot_build(p1)) 
    g2 <- ggplot_gtable(ggplot_build(p2)) 
    
    # function to remove selected elements from gtables, keeping widths 
    gtable_grob_remove <- function (g, what = "guide-box") { 
        require(gtable) 
        matches <- c(grepl(pattern = what, g$layout$name)) 
        g$layout <- g$layout[!matches, , drop = FALSE] 
        g$grobs <- g$grobs[!matches] 
        return(g) 
    } 
    
    # replace "axis-b" 
    g <- g1 
    pos <- c(subset(g$layout, name == "axis-b", se = t:r)) 
    g <- gtable_grob_remove(g, what = "axis-b") 
    g <- gtable_add_grob(g, g2$grobs[[which(g2$layout$name == "axis-b")]], 
        pos$t, pos$l, pos$b, pos$r, , name = "axis-b") 
    
    # replace "xlab" 
    pos <- c(subset(g$layout, name == "xlab", se = t:r)) 
    g <- gtable_grob_remove(g, what = "xlab") 
    g <- gtable_add_grob(g, g2$grobs[[which(g2$layout$name == "xlab")]], 
        pos$t, pos$l, pos$b, pos$r, , name = "xlab") 
    
    grid.newpage() 
    grid.draw(g) 
    

    일부의 P2 eleme와 P1이다

    여기 enter image description here

    p2 <- ggplot(data = df, aes(x = Year, y = value, group = variable, colour = variable, shape = variable)) + 
    geom_line(size = 2, show_guide = FALSE) + 
    geom_point(size = 4, show_guide = FALSE) + 
    theme(panel.grid.major.x = element_line(size = 1, colour = "darkred"), 
         panel.grid.minor.x = element_line(size = 1, colour = "darkred", linetype = "dotted")) + 
    theme(text = element_text(size = 20, colour = "darkred")) + 
    theme(axis.text = element_text(size = 20, colour = "darkred")) 
    

    가 P2이다 : 여기

    # Data 
    df <- structure(list(Year = c(1950, 2013, 1950, 2013), Country = structure(c(1L, 
    1L, 2L, 2L), .Label = c("France", "United States"), class = "factor"), 
    Category = c("Hourly minimum wage", "Hourly minimum wage", 
    "Hourly minimum wage", "Hourly minimum wage"), value = c(2.14, 
    9.43, 3.84, 7.25), variable = c("France (2013 euros)", 
    "France (2013 euros)", "United States (2013 dollars)", "United States (2013 dollars)" 
    ), Unit = c("2013 euros", "2013 euros", "2013 dollars", "2013 dollars" 
    )), .Names = c("Year", "Country", "Category", "value", "variable", 
    "Unit"), row.names = c(NA, 4L), class = "data.frame") 
    
    # Plot data with ggplot 
    library(ggplot2) 
    p1 <- ggplot(data = df, aes(x = Year, y = value, group = variable, colour = variable, shape = variable)) + 
    geom_line(size = 2, show_guide = FALSE) + 
    geom_point(size = 4, show_guide = FALSE) + 
    theme(panel.grid.major.x = element_line(size = 1, colour = "darkgreen"), 
         panel.grid.minor.x = element_line(size = 1, colour = "darkgreen", linetype = "dotted")) + 
    theme(text = element_text(size = 20, colour = "darkgreen")) + 
    theme(axis.text = element_text(size = 20, colour = "darkgreen")) 
    

    는 P1이고 국세청 :

    enter image description here

    G1 내가 그린 사람을 대체하는 라벨 및 수직 그리드 라인 축 빨간색 바닥을 원하는, G2는 빨간색, 녹색입니다.

    나는 축 레이블과 축 제목을 확인하는 데 성공했지만 여전히 수직 그리드 선 (축 축 눈금과 축 수평선)을 찾고 있습니다. 나는 그들이 panel 안에 있다고 상상하지만 어떻게 접근하고 변경 하는가?

    이전 메모에서 baptiste는 다른 요소를 식별하는 방법으로 names(ggplotGrob(p2)[["grobs"]][[4]][["children"]])을 제안했습니다. 다음을 반환합니다.

    names(ggplotGrob(p2)[["grobs"]][[4]][["children"]]) 
    [1] "grill.gTree.843"   "GRID.polyline.828"   
    [3] "geom_point.points.830"  "panel.border.zeroGrob.831" 
    

    그러나 여기에서 가져 오는 방법을 알지 못합니다. 또한, 첨부 된 번호, 예를 들면. .843 모든 세션마다 변경되므로이 숫자를 하드 코드하지 않는 방법을 찾고 싶습니다. 제안에 감사드립니다! 다른 답변에 따라

    답변

    4

    , 어디 믿을 수 없을만큼 지루한 학습 경험이었다 관심의 비트를 찾을 수있는 grobs 구조화 얼마나 학습의 과정에서,

    # locate the children 
    grill1 <- grepl("grill", 
           names(g1[["grobs"]][[4]][["children"]])) 
    grill2 <- grepl("grill", 
           names(g2[["grobs"]][[4]][["children"]])) 
    
    # swap the kids, the parents won't notice 
    g1[["grobs"]][[4]][["children"]][grill1] <- 
        g2[["grobs"]][[4]][["children"]][grill2] 
    
    
    grid.newpage() 
    grid.draw(g1) 
    

    enter image description here

    +0

    을이 고려 , 나는 당신의 접근법을 위에서 확장했다. 저는 이제 레이블과 패널 같은 것들을 교환 할 수 있습니다. 그러나 수직 그리드 선만 바꿔서 고민하고 있습니다 (솔루션에서 수평 그리드 선도 바뀌 었습니다. 이는 흰색이기 때문에 표시되지 않습니다). 나는 흥미를 끄는 비트를 잡아주고 바꿀 수있는 추악한 기능을 만들었다. 어리석은 것으로, 아마도 중복되고, 완전히 성공하지 못했다. https://gist.github.com/annoporci/f0c355fcd5ab4462a424 – PatrickT

    +0

    나는이 시점에서 네가 나에게 주었던 것과 궁극적 인 목적을 위해 필요한 것보다 더 많은 것을 얻었 기 때문에, 순수 학문적 관심사이고 더 이상 현실적인 타당성이 없다. :-) – PatrickT