How to apply cross-hatching to a polygon using the grid graphical system?
graphics, r, r-grid
Solution
As of R 4.1.0, grid got the `pattern` function which allows to repeat any other grob as a filling:
library(grid)
# Note that using absolute coordinates like "cm" for
# x and y does not work
cross <- grobTree(
linesGrob( x=unit(c(0,1),"npc"), y=unit(c(0,1),"npc")),
linesGrob( x=unit(c(0,1),"npc"), y=unit(c(1,0),"npc")))
cpat <- pattern(cross,
width = unit(1,"cm"),
height = unit(1,"cm"),
extend = "repeat")
rect <- rectGrob(
width = unit(5, "cm"),
height = unit(5, "cm"),
gp= gpar(fill = cpat))
grid.newpage()
grid.draw(rect)
(This answer was helped by this blog post)
Problem
Several functions in R's base graphical system, including `rect()` and `polygon()`, support cross-hatching via their `angle=` and `density=` arguments: ``` x = c(0, 0.5, 1, 0.5) y = c(0.5, 1, 0.5, 0) par(mar=c(0,0,0,0)) plot.new() polygon(x, y, angle=45, density=10) ``` How might I apply similar cross-hatching to a polygon drawn by the grid graphical system's `grid.polygon()` function: ``` library(grid) grid.newpage() grid.polygon(x,y) ``` I've looked in the documentation for `?grid.polygon` and `?gpar`, and have skimmed through Paul Murrel's book on R graphics, and have so far come up empty. Am I missing something obvious? If not, is there some simple hack which will make this possible?