How can I use grid to edit a ggplot2 object to add math expressions to facet labels?

后端 未结 1 1312
无人共我
无人共我 2020-12-09 13:24

I need to put Greek letters into facet labels using facet_wrap() in ggplot2. I found a Link describing the same for facet_grid(). I applied this for my data, using the follo

相关标签:
1条回答
  • 2020-12-09 14:22

    This example should get you started:

    library("ggplot2")
    library("grid")
    
    d <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) +
                geom_point() +
                facet_wrap(~Species)
    grob <- ggplotGrob(d)
    strip_elem <- grid.ls(getGrob(grob, "strip.text.x", grep=TRUE, global=TRUE))$name
    
    grob <- grid::editGrob(grob, strip_elem[1], label=expression(alpha[1]))
    grob <- grid::editGrob(grob, strip_elem[2], label=expression(beta^2))
    grob <- grid::editGrob(grob, strip_elem[3], label=expression(hat(gamma)))
    
    grid.draw(grob)
    

    modified grob

    Update: this works with ggplot2 version 0.9.3 (although using grid is a fragile way to modify ggplot2 graphics)

    grob[["grobs"]][["strip_t.1"]][["children"]][[2]][["label"]] <- expression(alpha[1])
    grob[["grobs"]][["strip_t.2"]][["children"]][[2]][["label"]] <- expression(beta^2)
    grob[["grobs"]][["strip_t.3"]][["children"]][[2]][["label"]] <- expression(hat(gamma))
    grid.draw(grob)
    
    0 讨论(0)
提交回复
热议问题