替换gtable中的ggplot元素:标签和网格线 [英] replacing elements of a ggplot inside a gtable: labels and gridlines

查看:368
本文介绍了替换gtable中的ggplot元素:标签和网格线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习使用 gtable 操作 ggplot 对象。 [这里有一个相关的问题,我问:拆除一个ggplot与网格和gtable ]



现在的问题是:


  1. 如何从一个gtable获取各种轴元素,并将它们放入另一个gtable中以替代现有元素?,特别是:替换垂直网格线(以及相应的tickmarks)。


    以下是一些代码和数字。

     #Data 
    df < - 结构(列表(年份= c(1950,2013,1950,2013),国家=结构(c(1L,
    1L,2L,2L),。标签= c(法国 ,美国),class =factor),
    Category = c(小时最低工资,小时最低工资,
    小时最低工资,小时最低工资) ,价值= c(2.14,
    9.43,3.84,7.25),变量= c(法国(2013欧元),
    法国(2013欧元),美国(2013美元) ,Un (2013美元)
    ),单位= c(2013年欧元,2013年欧元,2013美元,2013美元
    )),.Names = c( ,Country,Category,value,variable,
    Unit),row.names = c(NA,4L),class =data.frame)

    #使用ggplot绘制数据
    library(ggplot2)
    p1 < - ggplot(data = df,aes(x = Year,y = value,group = variable,color = variable,shape =变量))+
    geom_line(size = 2,show_guide = FALSE)+
    geom_point(size = 4,show_guide = FALSE)+
    theme(panel.grid.major.x = element_line (size = 1,color =darkgreen),
    panel.grid.minor.x = element_line(size = 1,color =darkgreen,linetype =dotted))+
    theme( text = element_text(size = 20,color =darkgreen))+
    theme(axis.text = element_text(size = 20,color =darkgreen))

    以下是p1:


      p2< / p> lt;  -  ggplot(data = df,aes(x = Year,y = value,group = variable,color = 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,color =darkred),
    panel.grid.minor。 x = element_line(size = 1,color =darkred,linetype =dotted))+
    theme(text = element_text(size = 20,color =darkred))+
    theme axis.text = element_text(size = 20,color =darkred))

    这是p2:



     #将p1的底部轴替换为p2的底部轴
    library(gtable)
    g1 < - ggplot_gtable(ggplot_build( p1))
    g2< - ggplot_gtable(ggplot_build(p2))

    #函数从gtables中删除选定的元素,保持宽度
    gtable_grob_remove< - function(g,what =guide-box){
    require(gtable)
    匹配< -c(grepl(pattern = what,g $ layout $ name))
    g $ layout< - g $ layout [!matches,drop = FALSE]
    g $ grobs< - g $ grobs [!matches]
    return(g)
    }

    #替换axis-b
    g< - g1
    pos < - c(子集(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)

    #替换xlab
    pos <-c(子集(g $ layout,name ==xlab, (g,g2 $ grobs [[which(g2 $ layout $ name ==))
    g < - gtable_grob_remove(g,what =xlab)
    g < - gtable_add_grob xlab)]],
    pos $ t,pos $ l,pos $ b,pos $ r,,name =xlab)

    grid.newpage()
    grid.draw(g)

    以下是p1中的一些p2元素:



    g1是绿色的,g2是红色的,我想要红底轴标签和垂直网格线来代替绿色的。


    我已经成功地识别了轴标签和轴标题,但我仍然在寻找垂直网格线(以及轴标记和轴水平线) !)。我想他们在面板中,但是如何访问它们并修改它们?



    在之前的评论中, baptiste建议使用名称(ggplotGrob(p2)[[grobs]] [[4]] [[children]])来识别不同的元素。这将返回:

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

    但是,我不知道如何从这里获取。而且,所附的数字,例如.843随着每个会话而改变,所以我想找到一种不硬编码这些数字的方法。感谢您的建议!

    解决方案

    基于其他答案,考虑一下,

     #找到孩子
    grill1< - grepl(grill,
    names(g1 [[grobs]] [[4]] [ [children]]))
    grill2< - grepl(grill,
    names(g2 [[grobs]] [[4]] [[children]]))

    #交换孩子,父母不会注意到
    g1 [[grobs]] [[4]] [[children]] [grill1]< -
    g2 [[grobs]] [[4]] [[children]] [grill2]


    grid.newpage()
    grid.draw (g1)


    I am learning to manipulate ggplot objects with gtable. [Here is a related question I asked: dismantling a ggplot with grid and gtable ]

    The present issue is:

    1. how to take various axis elements from one gtable and place them into another gtable in replacement of existing elements? and in particular: replace the vertical grid lines (and corresponding tickmarks).

    Below some code and figures.

    # 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"))
    

    Here is p1:

    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"))
    

    Here is p2:

    # 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)
    

    Here is p1 with some p2 elements:

    g1 is green, g2 is red, I want the red bottom axis labels and vertical grid lines to replace the green ones.

    I have been successful in identifying the axis labels and axis title, but I'm still looking for the vertical grid lines (and the axis tickmarks and the axis horizontal line too!). I imagine they are inside the panel, but how to access them and alter them?

    In a previous comment, baptiste suggested names(ggplotGrob(p2)[["grobs"]][[4]][["children"]]) as a way to identify different elements. This returns:

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

    However, I do not know how to take it from here. Also, the appended numbers, e.g. .843 change with every session, so I would like to find a way to not hardcode these numbers. Thanks for suggestions!

    解决方案

    based on the other answer, consider this,

    # 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)
    

    这篇关于替换gtable中的ggplot元素:标签和网格线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆