[R] type = 'b' with Grid

baptiste auguie baptiste.auguie at gmail.com
Thu Jun 4 21:34:04 CEST 2009


Dear all,

I feel like I've been reinventing the wheel with this code (implementing 
type = 'b' for Grid graphics),

http://econum.umh.ac.be/rwiki/doku.php?id=tips:graphics-grid:linesandpointsgrob

Has anyone here attempted this with success before? I found suggestions 
of overlapping large white points to mask the lines but it's not ideal.

I welcome any comments on the code. (e.g., should it perhaps use 
polylines rather than segments?, is there an obvious optimization to 
make?, ...)

Regards,

baptiste



# code reproduced below,

barbedGrob <- function( x = 1:10/12,
                        y = sin(1:10)/3+0.5,
                        size=1, shape=21, space=1,
                        colour="red", fill="blue",
                        linetype=1, linewidth=1){
 
 
n <- length(x)
 
dx <- diff(x)
dy <- diff(y)
 
# duplicate the points to make split segments
new.x <- rep(x, each=2)[-c(1, 2*length(x))]
new.y <- rep(y, each=2)[-c(1, 2*length(y))]
new.size <- rep(size, each=2, length=2*n)[-c(1, 2*n)]
 
length <- sqrt(dx^2 + dy^2) # length of initial segments
exclusion <- 0.5*space*convertX(unit(new.size, "char"), "npc", TRUE)
 
scaling <- exclusion / rep(length, each=2) # exclusion factor around 
each point
 
start <- seq(1, by=2, length(new.x)) # starting points
end <- seq(2, by=2, length(new.x)) # end points
 
x.start <- scaling[start] * dx[(start+1)/2] + new.x[start] # shift the 
points
y.start <- scaling[start] * dy[(start+1)/2] + new.y[start] # keeping the 
direction of the initial segments
 
x.end <- new.x[end] - scaling[end] * dx[end/2]
y.end <- new.y[end] - scaling[end] * dy[end/2]
 
grob.lines <- segmentsGrob(
    x0 = x.start, y0 = y.start,
    x1 = x.end, y1=y.end,
     default.units="native",
 gp = gpar(
   col = colour,
   lex = linewidth, lty = linetype, lineend = "butt"
 )
)
 
grob.points <- pointsGrob(x, y, pch=shape, size=unit(size, "char"),
    gp = gpar(
      col = colour,
      fill = fill,
      lex = linewidth, linejoin = "mitre"
    )
)
 
   gTree(children = gList(grob.lines,grob.points))
 
}
 
 
 
# example of use
g <-
barbedGrob(size=sample(1:3, 10, repl=T),
    fill=alpha("white", 0.3),
    col=alpha("cadetblue4", 0.8),
    linewidth=5, space=1.2)
pushViewport(vp=viewport(width=1, height=1))
grid.rect(gp=gpar(fill="thistle2"))
grid.grill(gp=gpar(col="lavenderblush1", lwd=3, lty=3))
grid.draw(g)



-- 
_____________________________

Baptiste Auguié

School of Physics
University of Exeter
Stocker Road,
Exeter, Devon,
EX4 4QL, UK

Phone: +44 1392 264187

http://newton.ex.ac.uk/research/emag




More information about the R-help mailing list