[R] Fill a polygon with a pattern

Duncan Murdoch murdoch at stats.uwo.ca
Tue Oct 9 02:31:34 CEST 2007

On 08/10/2007 5:42 PM, Alberto Monteiro wrote:
> What is the simplest (namely: minimum number of libraries or conflicts)
> way to fill a polygon with a pattern?
> For example, suppose I have (in a graphic file, like a jpeg) the 
> drawing of an "X". Then I fill a polygon (like a triangle) with
> this pattern, and get something like:
>    X  
>   XXX
> (where the border "X"s could be truncated).
> I searched the rimage package, but it seems that there is no
> such function.

Depending on the polygon, the simplest way might be to use rgl, and use 
texture mapping to repeat the X.  I think it would be something like this:

x <- c(0, 0.5, 1)
y <- c(0, 1, 0)
triangles3d(x, 0, y, texcoords=cbind(x, y)*6,
     col="white", specular="black", ambient="white")

(The col="white" says to paint the image on a white canvas; 
specular="black" turns off reflections, and ambient="white" makes it 
equally bright regardless of how you rotate it.  The texcoords argument 
gives coordinates in the image (only the fractional part counts), 
corresponding to the geometry coordinates specified as the first 3 args.)

You would replace the texture= argument with your own filename.  It 
needs to be a .png file, not a JPEG.

This is more difficult if the polygon isn't a triangle or a 
quadrilateral, because you'd have to break it down into those.  There's 
a function in gpclib that will triangulate a general polygon.

Duncan Murdoch

More information about the R-help mailing list