19
votes

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)

enter image description here

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)

enter image description here

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?

1
it's not possible. It's however possible via gridSVG (grid.patternFill)baptiste
@baptiste -- Good to know. Coming from you, I'll take that as +/definitive. Thanks, too, for the pointer to that gridSVG function.Josh O'Brien
i never really tried, and it's relatively recent I think. Here's an example, stat.auckland.ac.nz/~paul/Talks/London2013/barchart/barchart.Rbaptiste
@baptiste Unfortunately, I need this in a pdf, so I might just have to convert my polygons to a raster, and use that as a mask to extract a pattern from another raster image (as demonstrated in this Paul Murrel R-Journal article). Looks like your gridExtra::rpatternGrob might be helpful if I go in that direction.Josh O'Brien
personally, I'd give svg-to-pdf conversion a shot, maybe some recent tools or even Inkscape can do a decent job.baptiste

1 Answers

22
votes

Here's an example with gridSVG adapted from Paul Murrell's presentation

library(gridSVG)
library(grid)
x = c(0, 0.5, 1, 0.5)
y = c(0.5, 1, 0.5, 0)
grid.newpage()
grid.polygon(x,y, name="goodshape")

pat <- pattern(linesGrob(gp=gpar(col="black",lwd=3)),
  width = unit(5, "mm"), height = unit(5, "mm"),
  dev.width = 1, dev.height = 1)

# Registering pattern
registerPatternFill("pat", pat)
# Applying pattern fill
grid.patternFill("goodshape", label = "pat")

grid.export("test-pattern.svg")

enter image description here

more complex grobs are allowed as well, since svg takes care of the clipping.

enter image description here