How to add a border around a chart created via arrange.grid in gridExtra encompassing a set ggplot2 scatter plots

前端 未结 2 654
抹茶落季
抹茶落季 2020-12-14 21:17

I\'m using the code below:

# Libs
require(ggplot2); require(gridExtra); require(grid)

# Generate separate charts
chrts_list_scts <- list()

# Data
data(\         


        
相关标签:
2条回答
  • 2020-12-14 21:39

    you can add a rectGrob to the gtable

    grid.draw(gtable::gtable_add_grob(arrangeGrob(g, g, ncol=2),
                 rectGrob(gp=gpar(lwd=5, fill=NA)), 1, 1, 1, 2))
    

    NOTE: fill=NA or fill='transparent' is required otherwise the rectangle can mask the objects below it.

    0 讨论(0)
  • 2020-12-14 21:54

    1) Using the iris example (but further simplified) from the link provided in the question just add the last line. Modify the gpar(...) components (and possibly the width and height) to get different aesthetics. (This is not encapsulated in the grid.arrange call.)

    library(ggplot2)
    library(grid)
    library(gridExtra)
    
    g <- ggplot(iris, aes(Sepal.Width, Sepal.Length)) + geom_point()
    grid.arrange(g, g, ncol=2)
    
    
    # next line adds border
    grid.rect(width = .98, height = .98, gp = gpar(lwd = 2, col = "blue", fill = NA))
    

    (continued after plot)

    2) This is a variation of solution (1) in which on the plus side encapsulates both the graphics and border in the gt gTree by creating grobs to hold each. On the other hand it does involve some additional complexity:

    grid.newpage()
    ga <- arrangeGrob(g, g, ncol = 2)
    gb <- rectGrob(height = .98, width = .98, gp = gpar(lwd = 2, col = "blue", fill = NA)) # border, no fill
    gt <- gTree(children = gList(ga, gb))
    grid.draw(gt)
    
    0 讨论(0)
提交回复
热议问题