Drawing a grid grob on a scatterplot in R

46 views Asked by At

How to add a grid grob (polygon) on a scatterplot in R ? With graphics::polygon it is possible. But with grid::polygonGrob with "native" unit, the grob is not plotted.

rand <-  rnorm(3000, 1, 2)
plot(rand)
xy <- list(x = c(569.781985656951, 575.109507204421, 1917.64493716692, 
                 1917.64493716692), 
           y = c(2.28350942471649, -1.44814265497201, 
                 -1.44814265497201, 2.99591573083884))
polygon(xy$x, xy$y, border = "red")
grid.draw(grid::polygonGrob(x=xy$x, y=xy$y, 
                            default.units = "native",
                            gp = gpar(col = "blue", fill = "transparent")))

enter image description here

1

There are 1 answers

0
Crops On

This can be done using base Viewports() function of gridBase package. It creates a set of viewports corresponding to R base graphics.

rand <-  rnorm(3000, 1, 2)
plot(rand)
xy <- list(x = c(569.781985656951, 575.109507204421, 1917.64493716692, 
                 1917.64493716692), 
           y = c(2.28350942471649, -1.44814265497201, 
                 -1.44814265497201, 2.99591573083884))
polygon(xy$x, xy$y, border = "red")

vps <- gridBase::baseViewports()
pushViewport(vps$inner, vps$figure, vps$plot)
grid.draw(grid::polygonGrob(x=xy$x, y=xy$y, 
                            default.units = "native",
                            gp = gpar(col = "blue", fill = "transparent")))

enter image description here