[R] How to fill irregular polygons with patterns?
baptiste auguie
baptiste.auguie at googlemail.com
Fri Nov 18 22:48:51 CET 2011
Hi,
Two possible routes I can suggest:
1- export the plot in svg format, which supports natively the use of
filling patterns, e.g.
http://www.w3.org/TR/SVG/images/pservers/pattern01.svg
It's possible that the gridSVG package could help you automate the
process of "grid.garnish()-ing" the grobs; last time I looked I didn't
succeed. Otherwise, manual editing or a software like Inkscape can do
the trick.
2- grid.raster can help you use a polygon shape as a mask for another
picture. For example,
png("mask.png"); grid.circle(gp=gpar(fill="black")); dev.off()
png("pattern.png"); xy = expand.grid( x = seq(0,1, length=20),
y=seq(0,1, length=20)) ;
with(xy, grid.points(x, y, pch=21, gp=gpar(col="red", fill="blue",
lwd=2), def="npc"))
dev.off()
library(png)
m = readPNG("mask.png", native=FALSE)
p = readPNG("pattern.png", native=FALSE)
pattern <- matrix(rgb(p[,,1],p[,,2],p[,,3]),
nrow=dim(p)[1])
mask <- matrix(rgb(m[,,1],m[,,2],m[,,3]),
nrow=dim(m)[1])
pattern[mask == "#FFFFFF"] <- "#FFFFFF"
grid.raster(pattern)
HTH,
baptiste
On 19 November 2011 07:03, Ortiz, John <OrtizJ at si.edu> wrote:
>
> Hi,
>
> I'm looking the best way to fill irregular polygons with patterns,
> Something like the function grid.pattern do, but my case is with
> irregular polygons.
>
> Whit this script I can get it, but I'm looking for an "elegant" solution..
>
> library(grid)
>
> grid.polygon(x=c(0.2, 0.8, 0.6, 0.6, 0.8, 0.2),
> y=c(0.2, 0.2, 0.3, 0.5, 0.7,0.7),
> gp=gpar(fill="grey", alpha=0.9))
> tmp=seq(0.225,0.7,0.075)
> for(i in 1:length(tmp)) {
> grid.abline(intercep=tmp[i],
> slope=0, units="npc",
> range=c(0.21,0.79),
> gp=gpar(lty=c("F8","2"), lwd=1.1))
> }
> tmp2=seq(0.265,0.685,0.075)
> for(i in 1:length(tmp2)) {
> grid.abline(intercep=tmp2[i],
> slope=0, units="npc",
> range=c(0.225,0.775),
> gp=gpar(lty="F8", lwd=1.1, col="red"))
> }
>
> grid.polygon(x=c(0.8, 0.6, 0.6, 0.8),
> y=c(0.2, 0.3, 0.5, 0.7),
> gp=gpar(fill="white", col="white"))
>
> grid.polygon(x=c(0.2, 0.8, 0.6, 0.6, 0.8, 0.2),
> y=c(0.2, 0.2, 0.3, 0.5, 0.7,0.7),
> gp=gpar(fill="transparent"))
>
> ### other example
>
>
> grid.polygon(x=c(0.2, 0.8, 0.6, 0.6, 0.8, 0.2),
> y=c(0.2, 0.2, 0.3, 0.5, 0.7,0.7),
> gp=gpar(fill="yellow", alpha=0.8))
>
> grid.points(x=runif(500, min=0.21, max=0.79),
> y=runif(500, min=0.21, max=0.69),
> default.units="npc", pch=c(20,21),
> gp=gpar(cex=c(0.3, 0.5, 0.6), alpha=0.7))
>
> grid.polygon(x=c(0.8, 0.6, 0.6, 0.8),
> y=c(0.2, 0.3, 0.5, 0.7),
> gp=gpar(fill="white", col="white",
> lwd=0, alpha=1))
>
> grid.polygon(x=c(0.2, 0.8, 0.6, 0.6, 0.8, 0.2),
> y=c(0.2, 0.2, 0.3, 0.5, 0.7,0.7),
> gp=gpar(fill="transparent", alpha=1))
>
>
> Thanks in advance,
>
> John
>
More information about the R-help
mailing list