### R code from vignette source 'gridsvg.Rnw'

###################################################
### code chunk number 1: gridsvg.Rnw:88-89
###################################################
options(prompt="R> ", continue="R+ ", useFancyQuotes=FALSE)


###################################################
### code chunk number 2: gridsvg.Rnw:261-262
###################################################
library("grid")


###################################################
### code chunk number 3: gridscene
###################################################
topvp <- viewport(y=1, just="top", name="topvp",
                  height=unit(1, "lines"))
botvp <- viewport(y=0, just="bottom", name="botvp",
                  height=unit(1, "npc") - unit(1, "lines"))
grid.rect(gp=gpar(fill="grey"), vp=topvp, name="toprect")
grid.rect(vp=botvp, name="botrect")


###################################################
### code chunk number 4: gridsvg.Rnw:287-288
###################################################
library("gridSVG")


###################################################
### code chunk number 5: gridsceneweb (eval = FALSE)
###################################################
## gridToSVG("gridscene.svg")


###################################################
### code chunk number 6: gridsvg.Rnw:295-297
###################################################
topvp <- viewport(y=1, just="top", name="topvp",
                  height=unit(1, "lines"))
botvp <- viewport(y=0, just="bottom", name="botvp",
                  height=unit(1, "npc") - unit(1, "lines"))
grid.rect(gp=gpar(fill="grey"), vp=topvp, name="toprect")
grid.rect(vp=botvp, name="botrect")
gridToSVG("gridscene.svg")


###################################################
### code chunk number 7: gridsvg.Rnw:331-333
###################################################
widthValues <- unit(c(1, 1), c("npc", "in"))
widthValues


###################################################
### code chunk number 8: gridanimate (eval = FALSE)
###################################################
## grid.animate("toprect", width=widthValues, duration=3)
## grid.animate("botrect", width=widthValues, duration=3)


###################################################
### code chunk number 9: gridanimateweb (eval = FALSE)
###################################################
## gridToSVG("gridanim.svg")


###################################################
### code chunk number 10: gridsvg.Rnw:350-354
###################################################
grid.newpage()
topvp <- viewport(y=1, just="top", name="topvp",
                  height=unit(1, "lines"))
botvp <- viewport(y=0, just="bottom", name="botvp",
                  height=unit(1, "npc") - unit(1, "lines"))
grid.rect(gp=gpar(fill="grey"), vp=topvp, name="toprect")
grid.rect(vp=botvp, name="botrect")
grid.animate("toprect", width=widthValues, duration=3)
grid.animate("botrect", width=widthValues, duration=3)
gridToSVG("gridanim.svg")


###################################################
### code chunk number 11: gridhyper (eval = FALSE)
###################################################
## grid.text("take me there", vp=topvp, name="hypertext")
## grid.hyperlink("hypertext", "http://www.r-project.org")


###################################################
### code chunk number 12: gridhyperweb (eval = FALSE)
###################################################
## gridToSVG("gridhyper.svg")


###################################################
### code chunk number 13: gridsvg.Rnw:392-396
###################################################
grid.newpage()
topvp <- viewport(y=1, just="top", name="topvp",
                  height=unit(1, "lines"))
botvp <- viewport(y=0, just="bottom", name="botvp",
                  height=unit(1, "npc") - unit(1, "lines"))
grid.rect(gp=gpar(fill="grey"), vp=topvp, name="toprect")
grid.rect(vp=botvp, name="botrect")
grid.text("take me there", vp=topvp, name="hypertext")
grid.hyperlink("hypertext", "http://www.r-project.org")
gridToSVG("gridhyper.svg")


###################################################
### code chunk number 14: gridmouse (eval = FALSE)
###################################################
## grid.garnish("botrect", 
##              onmousedown="alert('ouch!')",
##              "pointer-events"="all")


###################################################
### code chunk number 15: gridmouseweb (eval = FALSE)
###################################################
## gridToSVG("gridmouse.svg")


###################################################
### code chunk number 16: gridsvg.Rnw:431-436
###################################################
grid.newpage()
topvp <- viewport(y=1, just="top", name="topvp",
                  height=unit(1, "lines"))
botvp <- viewport(y=0, just="bottom", name="botvp",
                  height=unit(1, "npc") - unit(1, "lines"))
grid.rect(gp=gpar(fill="grey"), vp=topvp, name="toprect")
grid.rect(vp=botvp, name="botrect")
grid.text("take me there", vp=topvp, name="hypertext")
grid.hyperlink("hypertext", "http://www.r-project.org")
grid.garnish("botrect", 
             onmousedown="alert('ouch!')",
             "pointer-events"="all")
gridToSVG("gridmouse.svg")


###################################################
### code chunk number 17: gridscript (eval = FALSE)
###################################################
## grid.garnish("toprect", 
##              onmousedown="allblack()",
##              "pointer-events"="all")
## grid.script("
##   allblack = function() {
##     rect = document.getElementById('toprect.1');
##     rect.setAttribute('style', 'fill:black');
##   }")


###################################################
### code chunk number 18: gridscriptweb (eval = FALSE)
###################################################
## gridToSVG("gridscript.svg")


###################################################
### code chunk number 19: gridsvg.Rnw:480-486
###################################################
grid.newpage()
topvp <- viewport(y=1, just="top", name="topvp",
                  height=unit(1, "lines"))
botvp <- viewport(y=0, just="bottom", name="botvp",
                  height=unit(1, "npc") - unit(1, "lines"))
grid.rect(gp=gpar(fill="grey"), vp=topvp, name="toprect")
grid.rect(vp=botvp, name="botrect")
grid.text("take me there", vp=topvp, name="hypertext")
grid.hyperlink("hypertext", "http://www.r-project.org")
grid.garnish("botrect", 
             onmousedown="alert('ouch!')",
             "pointer-events"="all")
grid.garnish("toprect", 
             onmousedown="allblack()",
             "pointer-events"="all")
grid.script("
  allblack = function() {
    rect = document.getElementById('toprect.1');
    rect.setAttribute('style', 'fill:black');
  }")
gridToSVG("gridscript.svg")


###################################################
### code chunk number 20: gridsvg.Rnw:515-516
###################################################
library("lattice")


###################################################
### code chunk number 21: xyplot
###################################################
xyplot(Sepal.Length ~ Sepal.Width | Species, iris)


###################################################
### code chunk number 22: latticehyperlink
###################################################
grid.hyperlink("plot_01.textr.strip.1.1", 
               "http://en.wikipedia.org/wiki/Iris_flower_data_set")
grid.hyperlink("plot_01.textr.strip.1.2", 
               "http://en.wikipedia.org/wiki/Iris_virginica")
grid.hyperlink("plot_01.textr.strip.2.1", 
               "http://en.wikipedia.org/wiki/Iris_versicolor")


###################################################
### code chunk number 23: lh
###################################################
gridToSVG("latticehyper.svg")


###################################################
### code chunk number 24: latticehyper
###################################################
xyplot(Sepal.Length ~ Sepal.Width | Species, iris)
grid.hyperlink("plot_01.textr.strip.1.1", 
               "http://en.wikipedia.org/wiki/Iris_flower_data_set")
grid.hyperlink("plot_01.textr.strip.1.2", 
               "http://en.wikipedia.org/wiki/Iris_virginica")
grid.hyperlink("plot_01.textr.strip.2.1", 
               "http://en.wikipedia.org/wiki/Iris_versicolor")
gridToSVG("latticehyper.svg")


###################################################
### code chunk number 25: gridls (eval = FALSE)
###################################################
## grid.ls(viewports=TRUE, fullNames=TRUE, print=grobPathListing)


###################################################
### code chunk number 26: gridscenels
###################################################
grid.newpage()
topvp <- viewport(y=1, just="top", name="topvp",
                  height=unit(1, "lines"))
botvp <- viewport(y=0, just="bottom", name="botvp",
                  height=unit(1, "npc") - unit(1, "lines"))
grid.rect(gp=gpar(fill="grey"), vp=topvp, name="toprect")
grid.rect(vp=botvp, name="botrect")
grid.ls(viewports=TRUE, fullNames=TRUE, print=grobPathListing)


###################################################
### code chunk number 27: gridscenetosvg (eval = FALSE)
###################################################
## gridToSVG("gridscene.svg")


###################################################
### code chunk number 28: gridscenesvg
###################################################
topvp <- viewport(y=1, just="top", name="topvp",
                  height=unit(1, "lines"))
botvp <- viewport(y=0, just="bottom", name="botvp",
                  height=unit(1, "npc") - unit(1, "lines"))
grid.rect(gp=gpar(fill="grey"), vp=topvp, name="toprect")
grid.rect(vp=botvp, name="botrect")
gridToSVG("gridscene.svg")


###################################################
### code chunk number 29: gridsvg.Rnw:616-617
###################################################
library("XML")


###################################################
### code chunk number 30: gridsvg.Rnw:620-630
###################################################
presentationAttributes <-
    c("stroke", "stroke-opacity",
      "fill", "fill-opacity",
      "opacity",
      "font-weight", "font-style", "font-family", "fonts-size",
      "stroke-dasharray", "stroke-width",
      "stroke-linecap", "stroke-linejoin", "stroke-miterlimit")
removePresentation <- function(node) {
    removeAttributes(node, .attrs=presentationAttributes)
}


###################################################
### code chunk number 31: gridsvg.Rnw:631-640
###################################################
gridscenesvg <- xmlParse("gridscene.svg")
toprect <- getNodeSet(gridscenesvg,
                      "//svg:rect[@id='toprect.1']",
                      c(svg="http://www.w3.org/2000/svg"))[[1]]
removePresentation(toprect)
botrect <- getNodeSet(gridscenesvg,
                      "//svg:rect[@id='botrect.1']",
                      c(svg="http://www.w3.org/2000/svg"))[[1]]
removePresentation(botrect)


###################################################
### code chunk number 32: textgrob
###################################################
grid.text("take me there", name="sampleText")


###################################################
### code chunk number 33: textgrobsvg
###################################################
grid.text("take me there", name="sampleText")
gridToSVG("textgrob.svg")


###################################################
### code chunk number 34: gridsvg.Rnw:688-696
###################################################
textgrobsvg <- xmlParse("textgrob.svg")
gsvg <- getNodeSet(textgrobsvg,
                   "//svg:g[@id='sampleText.1']",
                   c(svg="http://www.w3.org/2000/svg"))[[1]]
textsvg <- getNodeSet(gsvg, "svg:g/svg:text",
                      c(svg="http://www.w3.org/2000/svg"))[[1]]
devnull <- removePresentation(textsvg)
cat(saveXML(gsvg))


###################################################
### code chunk number 35: pointsgrob
###################################################
pushViewport(viewport())
grid.points(1:2/3, 1:2/3, pch=c(1, 10), name="symbols")


###################################################
### code chunk number 36: pointsgrobsvg
###################################################
pushViewport(viewport())
grid.points(1:2/3, 1:2/3, pch=c(1, 10), name="symbols")
gridToSVG("pointsgrob.svg")


###################################################
### code chunk number 37: gridsvg.Rnw:738-759
###################################################
pointsgrobsvg <- xmlParse("pointsgrob.svg")
circlesvg <- getNodeSet(pointsgrobsvg,
                   "//svg:circle[@id='symbols.1']",
                   c(svg="http://www.w3.org/2000/svg"))[[1]]
removePresentation(circlesvg)
symbolsvg <- getNodeSet(pointsgrobsvg, 
                        "//svg:g[@id='symbols.2']",
                        c(svg="http://www.w3.org/2000/svg"))[[1]]
poly1svg <- getNodeSet(pointsgrobsvg, 
                       "//svg:polyline[@id='symbols.2.1']",
                       c(svg="http://www.w3.org/2000/svg"))[[1]]
devnull <- removePresentation(poly1svg)
poly2svg <- getNodeSet(pointsgrobsvg, 
                       "//svg:polyline[@id='symbols.2.2']",
                       c(svg="http://www.w3.org/2000/svg"))[[1]]
devnull <- removePresentation(poly2svg)
circle2svg <- getNodeSet(pointsgrobsvg, 
                         "//svg:circle[@id='symbols.2.3']",
                         c(svg="http://www.w3.org/2000/svg"))[[1]]
devnull <- removePresentation(circle2svg)
cat(saveXML(symbolsvg))


###################################################
### code chunk number 38: arrowgrobsrc
###################################################
grid.segments(0, 0, 1, 1, arrow=arrow(), name="lineWithArrow")


###################################################
### code chunk number 39: arrowgrob
###################################################
pushViewport(viewport(width=.8, height=.8))
grid.segments(0, 0, 1, 1, arrow=arrow(), name="lineWithArrow")


###################################################
### code chunk number 40: arrowgrobsvg
###################################################
grid.segments(0, 0, 1, 1, arrow=arrow(), name="lineWithArrow")
gridToSVG("arrowgrob.svg")


###################################################
### code chunk number 41: gridsvg.Rnw:786-812
###################################################
# Function to break a long line of SVG code
#   'text' is the SVG text (possibly containing newlines)
#   'element' gives the name of the element whose line we want to break
#             This is used to find the line to break
#   'attribs' gives one or more attribute names that want to break on
#   'anchor'  gives the attribute name that the new lines should line up with
breakLongLine <- function(text, element, attribs, anchor,
                          perl=FALSE) {
    text <- strsplit(text, "\n")[[1]]
    line <- grep(element, text, perl=perl)
    for (l in line) {
        newline <- text[l]
        indent <- regexpr(anchor, newline, perl=perl)
        for (i in attribs) {
            # Wrap attrib names in parentheses so can use \\1 in replacement text
            # This allows regular expression in attrib name
            newline <- gsub(paste("(", i, ")", sep=""), 
                            paste("\n", 
                                  paste(rep(" ", indent - 1), collapse=""),
                                  "\\1", sep=""),
                            newline, perl=perl)
        }
        text[l] <- newline
    }
    paste(text, collapse="\n")
} 


###################################################
### code chunk number 42: gridsvg.Rnw:815-829
###################################################
arrowgrobsvg <- xmlParse("arrowgrob.svg")
markersvg <- getNodeSet(arrowgrobsvg, "//svg:defs",
                        c(svg="http://www.w3.org/2000/svg"))[[1]]
devnull <- removeChildren(markersvg, kids=list(1))
markerpathsvg <- getNodeSet(markersvg, "//svg:path",
                            c(svg="http://www.w3.org/2000/svg"))[[1]]
devnull <- removePresentation(markerpathsvg)
polylinesvg <- getNodeSet(arrowgrobsvg, "//svg:polyline",
                          c(svg="http://www.w3.org/2000/svg"))[[1]]
devnull <- removePresentation(polylinesvg)
cat(breakLongLine(saveXML(markersvg),
                  "<marker", c("overflow", "markerHeight"), "id"))
cat(breakLongLine(saveXML(polylinesvg),
                  "<polyline", "marker-end", "id"))


###################################################
### code chunk number 43: circlegrob
###################################################
grid.circle(x=1:3/4, y=1:3/4, r=0.1, name="circles")


###################################################
### code chunk number 44: circlegrobsvg
###################################################
grid.circle(x=1:3/4, y=1:3/4, r=0.1, name="circles")
gridToSVG("circlegrob.svg")


###################################################
### code chunk number 45: gridsvg.Rnw:855-863
###################################################
circlegrobsvg <- xmlParse("circlegrob.svg")
gsvg <- getNodeSet(circlegrobsvg,
                   "//svg:g[@id='circles']",
                   c(svg="http://www.w3.org/2000/svg"))[[1]]
circlesvg <- getNodeSet(gsvg, "svg:circle",
                      c(svg="http://www.w3.org/2000/svg"))
devnull <- lapply(circlesvg, removePresentation)
cat(saveXML(gsvg))


###################################################
### code chunk number 46: gridsvg.Rnw:872-879
###################################################
gridscenesvg <- xmlParse("gridscene.svg")
toprectg <- getNodeSet(gridscenesvg,
                      "//svg:g[@id='toprect']",
                      c(svg="http://www.w3.org/2000/svg"))[[1]]
toprect <- toprectg["rect"][[1]]
devnull <- removePresentation(toprect)
cat(saveXML(toprectg))


###################################################
### code chunk number 47: gridsvg.Rnw:926-927 (eval = FALSE)
###################################################
## grid.rect(gp=gpar(fill="grey"), vp=topvp, name="toprect")


###################################################
### code chunk number 48: gridsvg.Rnw:938-967
###################################################
gridscenesvg <- xmlParse("gridscene.svg")
gridsvg <- getNodeSet(gridscenesvg,
                      "//svg:g[@id='gridSVG']",
                      c(svg="http://www.w3.org/2000/svg"))[[1]]
gridsvgchild <- getNodeSet(gridscenesvg,
                           "//svg:g[@id='gridSVG']/svg:g",
                           c(svg="http://www.w3.org/2000/svg"))[[1]]
toprect <- getNodeSet(gridscenesvg,
                      "//svg:rect[@id='toprect.1']",
                      c(svg="http://www.w3.org/2000/svg"))[[1]]
# Make the <rect> element the only child of the gridsvg element
devnull <- removeChildren(gridsvg, kids=xmlChildren(gridsvg))
devnull <- addChildren(gridsvg, kids=list(toprect))
cat(gsub(", ", ",", 
         gsub("</g>", "\n</g>",
              gsub("( +<rect)", "\n\\1",
                   breakLongLine(breakLongLine(saveXML(gridsvg),
                                               "<rect", 
                                               c("fill=", "fill-opacity"),
                                               "id"),
                                 "<g", 
                                 c("fill=", "stroke=", "stroke-dasharray",
                                   "font-size", 
                                   "font-family", 
                                   "(?<= )opacity", "stroke-linecap",
                                   "stroke-opacity"), 
                                 "id",
                                 perl=TRUE)))))
# Remove the children of the


###################################################
### code chunk number 49: gridsvg.Rnw:997-1008
###################################################
gridscenesvg <- xmlParse("gridscene.svg")
removeStyle <- function(node) {
    removePresentation(node)
    children <- xmlChildren(node)
    if (length(children) > 0)
        lapply(children, removeStyle)
    invisible()
}
invisible(lapply(xmlChildren(gridscenesvg), removeStyle))
cat(breakLongLine(saveXML(gridscenesvg),
                  "<svg", c("xmlns:xlink", "width"), "xmlns"))


###################################################
### code chunk number 50: gtree
###################################################
tg <- textGrob("this is a gTree", name="textchild")
rg <- rectGrob(width=grobWidth(tg) + unit(2, "mm"), 
               height=unit(1, "lines"),
               gp=gpar(col=NA, fill="grey"), name="rectchild")
textWithBG <- gTree(children=gList(rg, tg), name="gtree")


###################################################
### code chunk number 51: gtreefig
###################################################
grid.draw(textWithBG)


###################################################
### code chunk number 52: gridls (eval = FALSE)
###################################################
## grid.ls(fullNames=TRUE)


###################################################
### code chunk number 53: gridsvg.Rnw:1057-1059
###################################################
grid.draw(textWithBG)
grid.ls(fullNames=TRUE)


###################################################
### code chunk number 54: gridsvg.Rnw:1067-1070
###################################################
grid.newpage()
grid.draw(textWithBG)
gridToSVG("gtree.svg")


###################################################
### code chunk number 55: gridsvg.Rnw:1073-1086
###################################################
gtreesvg <- xmlParse("gtree.svg")
gtree <- getNodeSet(gtreesvg,
                     "//svg:g[@id='gtree']",
                     c(svg="http://www.w3.org/2000/svg"))[[1]]
text <- getNodeSet(gtreesvg,
                   "//svg:text",
                   c(svg="http://www.w3.org/2000/svg"))[[1]]
devnull <- removePresentation(text)
rect <- getNodeSet(gtreesvg,
                   "//svg:rect",
                   c(svg="http://www.w3.org/2000/svg"))[[1]]
devnull <- removePresentation(rect)
cat(saveXML(gtree))


###################################################
### code chunk number 56: font
###################################################
grid.text("font test", gp=gpar(fontfamily="Helvetica"),
          name="font")


###################################################
### code chunk number 57: gridsvg.Rnw:1121-1124
###################################################
grid.newpage()
grid.text("font test", gp=gpar(fontfamily="Helvetica"),
          name="font")
gridToSVG("font.svg")


###################################################
### code chunk number 58: gridsvg.Rnw:1128-1135
###################################################
fontsvg <- xmlParse("font.svg")
font <- getNodeSet(fontsvg,
                   "//svg:g[@id='font']",
                   c(svg="http://www.w3.org/2000/svg"))[[1]]
cat(gsub(", ", ",", 
         breakLongLine(saveXML(font),
                       "<text", c("font-family", "fill="), "x=")))


###################################################
### code chunk number 59: gridsvg.Rnw:1146-1149
###################################################
fontstacks <- getSVGFonts()
fontstacks$mono <- c("Inconsolata", fontstacks$mono)
setSVGFonts(fontstacks)


###################################################
### code chunk number 60: gridsvg.Rnw:1154-1155
###################################################
getSVGFonts()$mono


###################################################
### code chunk number 61: hypertext
###################################################
grid.text("take me there", name="hypertext")
grid.hyperlink("hypertext", href="http://www.r-project.org")


###################################################
### code chunk number 62: gridget (eval = FALSE)
###################################################
## grid.get("hypertext")


###################################################
### code chunk number 63: gridsvg.Rnw:1195-1197
###################################################
grid.text("take me there", name="hypertext")
grid.hyperlink("hypertext", href="http://www.r-project.org")
grid.get("hypertext")


###################################################
### code chunk number 64: gridsvg.Rnw:1205-1208
###################################################
grid.newpage()
grid.text("take me there", name="hypertext")
grid.hyperlink("hypertext", href="http://www.r-project.org")
gridToSVG("hypertext.svg")


###################################################
### code chunk number 65: gridsvg.Rnw:1211-1220
###################################################
hypertextsvg <- xmlParse("hypertext.svg")
anchor <- getNodeSet(hypertextsvg,
                     "//svg:a",
                     c(svg="http://www.w3.org/2000/svg"))[[1]]
text <- getNodeSet(hypertextsvg,
                   "//svg:text",
                   c(svg="http://www.w3.org/2000/svg"))[[1]]
devnull <- removePresentation(text)
cat(saveXML(anchor))


###################################################
### code chunk number 66: animcircle
###################################################
grid.circle(x=.2, r=.1, 
            gp=gpar(fill="black"), name="oneCircle")
grid.animate("oneCircle", x=c(.2, .8))


###################################################
### code chunk number 67: gridget (eval = FALSE)
###################################################
## grid.get("oneCircle")


###################################################
### code chunk number 68: gridsvg.Rnw:1255-1258
###################################################
grid.newpage()
grid.circle(x=.2, r=.1, 
            gp=gpar(fill="black"), name="oneCircle")
grid.animate("oneCircle", x=c(.2, .8))
grid.get("oneCircle")


###################################################
### code chunk number 69: gridsvg.Rnw:1264-1267
###################################################
grid.newpage()
grid.circle(x=.2, r=.1, 
            gp=gpar(fill="black"), name="oneCircle")
grid.animate("oneCircle", x=c(.2, .8))
gridToSVG("animcircle.svg")


###################################################
### code chunk number 70: gridsvg.Rnw:1270-1284
###################################################
animcirclesvg <- xmlParse("animcircle.svg")
animate <- getNodeSet(animcirclesvg,
                      "//svg:animate",
                      c(svg="http://www.w3.org/2000/svg"))[[1]]
cat(breakLongLine(saveXML(animate), 
                  "<animate", c("begin", "values"), "xlink"))
circleg <- getNodeSet(animcirclesvg,
                      "//svg:g[@id='oneCircle']",
                      c(svg="http://www.w3.org/2000/svg"))[[1]]
circle <- getNodeSet(animcirclesvg,
                     "//svg:circle[@id='oneCircle.1']",
                     c(svg="http://www.w3.org/2000/svg"))[[1]]
devnull <- removePresentation(circle)
cat(saveXML(circleg))


###################################################
### code chunk number 71: twocircles
###################################################
grid.circle(x=c(.2, .8), y=c(.2, .8), 
            r=.1, gp=gpar(fill="black"), name="twoCircles")


###################################################
### code chunk number 72: animvalues
###################################################
animValues <- cbind(c(.2, .8), c(.8, .2))
animValues


###################################################
### code chunk number 73: animtwocircles (eval = FALSE)
###################################################
## grid.animate("twoCircles", x=animValues)


###################################################
### code chunk number 74: gridsvg.Rnw:1320-1324
###################################################
grid.newpage()
grid.circle(x=c(.2, .8), y=c(.2, .8), 
            r=.1, gp=gpar(fill="black"), name="twoCircles")
grid.animate("twoCircles", x=animValues)
gridToSVG("twocircles.svg")


###################################################
### code chunk number 75: gridsvg.Rnw:1327-1351
###################################################
twocirclessvg <- xmlParse("twocircles.svg")
animate <- getNodeSet(twocirclessvg,
                      "//svg:animate",
                      c(svg="http://www.w3.org/2000/svg"))
invisible(lapply(animate, 
                 function(x) { 
                     cat(breakLongLine(saveXML(x), 
                                       "<animate", 
                                       c("begin", "values"), 
                                       "xlink"),
                         "\n")
                 }))
circleg <- getNodeSet(twocirclessvg,
                      "//svg:g[@id='twoCircles']",
                      c(svg="http://www.w3.org/2000/svg"))[[1]]
circle1 <- getNodeSet(twocirclessvg,
                     "//svg:circle[@id='twoCircles.1']",
                     c(svg="http://www.w3.org/2000/svg"))[[1]]
circle2 <- getNodeSet(twocirclessvg,
                     "//svg:circle[@id='twoCircles.2']",
                     c(svg="http://www.w3.org/2000/svg"))[[1]]
devnull <- removePresentation(circle1)
devnull <- removePresentation(circle2)
cat(saveXML(circleg))


###################################################
### code chunk number 76: animgroupcircles (eval = FALSE)
###################################################
## grid.circle(x=c(.2, .8), y=c(.2, .8), 
##             r=.1, gp=gpar(fill="black"), name="groupCircles")
## grid.animate("groupCircles", 
##              visibility=c("visible", "hidden"),
##              begin=1, duration=0.01,
##              group=TRUE)


###################################################
### code chunk number 77: gridsvg.Rnw:1371-1374
###################################################
grid.newpage()
grid.circle(x=c(.2, .8), y=c(.2, .8), 
            r=.1, gp=gpar(fill="black"), name="groupCircles")
grid.animate("groupCircles", 
             visibility=c("visible", "hidden"),
             begin=1, duration=0.01,
             group=TRUE)
gridToSVG("groupcircles.svg")


###################################################
### code chunk number 78: gridsvg.Rnw:1377-1401
###################################################
groupcirclessvg <- xmlParse("groupcircles.svg")
animate <- getNodeSet(groupcirclessvg,
                      "//svg:animate",
                      c(svg="http://www.w3.org/2000/svg"))
invisible(lapply(animate, 
                 function(x) { 
                     cat(breakLongLine(saveXML(x), 
                                       "<animate", 
                                       c("begin", "values"), 
                                       "xlink"),
                         "\n")
                 }))
circleg <- getNodeSet(groupcirclessvg,
                      "//svg:g[@id='groupCircles']",
                      c(svg="http://www.w3.org/2000/svg"))[[1]]
circle1 <- getNodeSet(groupcirclessvg,
                     "//svg:circle[@id='groupCircles.1']",
                     c(svg="http://www.w3.org/2000/svg"))[[1]]
circle2 <- getNodeSet(groupcirclessvg,
                     "//svg:circle[@id='groupCircles.2']",
                     c(svg="http://www.w3.org/2000/svg"))[[1]]
devnull <- removePresentation(circle1)
devnull <- removePresentation(circle2)
cat(saveXML(circleg))


###################################################
### code chunk number 79: gridsvg.Rnw:1427-1428
###################################################
animUnit(unit(c(.2, .8), "npc"))


###################################################
### code chunk number 80: gridsvg.Rnw:1436-1437
###################################################
animUnit(unit(c(.2, .8, .8, .2), "npc"), id=rep(1:2, each=2))


###################################################
### code chunk number 81: gridsvg.Rnw:1445-1446
###################################################
animUnit(unit(c(.2, .8, .8, .2), "npc"), timeid=rep(1:2, each=2))


###################################################
### code chunk number 82: gridsvg.Rnw:1453-1456
###################################################
animUnit(unit(c(.2, .8, .8, .2, .1, .9, .9, .1), "npc"), 
         timeid=rep(rep(1:2, each=2), 2), 
         id=rep(1:2, each=4))


###################################################
### code chunk number 83: gridscript
###################################################
grid.script(filename="script.js", name="script")


###################################################
### code chunk number 84: gridsvg.Rnw:1492-1495
###################################################
grid.newpage()
grid.script(filename="script.js", name="script")
gridToSVG("script.svg")


###################################################
### code chunk number 85: gridsvg.Rnw:1498-1503
###################################################
scriptsvg <- xmlParse("script.svg")
script <- getNodeSet(scriptsvg,
                     "//svg:script",
                     c(svg="http://www.w3.org/2000/svg"))[[1]]
cat(saveXML(script))


###################################################
### code chunk number 86: scriptembed
###################################################
grid.script("document.onload = alert('hi');",
            name="embeddedScript")


###################################################
### code chunk number 87: gridsvg.Rnw:1521-1524
###################################################
grid.newpage()
grid.script("document.onload = alert('hi');",
            name="embeddedScript")
gridToSVG("scriptEmbed.svg")


###################################################
### code chunk number 88: gridsvg.Rnw:1527-1532
###################################################
scriptembedsvg <- xmlParse("scriptEmbed.svg")
scriptembed <- getNodeSet(scriptembedsvg,
                          "//svg:script",
                          c(svg="http://www.w3.org/2000/svg"))[[1]]
cat(saveXML(scriptembed))


###################################################
### code chunk number 89: gridgarnish
###################################################
grid.circle(r=.1, gp=gpar(fill="black"), name="clickme")
grid.garnish("clickme", 
             onmousedown="alert('ouch!')",
             "pointer-events"="all")


###################################################
### code chunk number 90: gridsvg.Rnw:1566-1569
###################################################
grid.newpage()
grid.circle(r=.1, gp=gpar(fill="black"), name="clickme")
grid.garnish("clickme", 
             onmousedown="alert('ouch!')",
             "pointer-events"="all")
gridToSVG("gridgarnish.svg")


###################################################
### code chunk number 91: gridsvg.Rnw:1572-1581
###################################################
gridgarnishsvg <- xmlParse("gridgarnish.svg")
circleg <- getNodeSet(gridgarnishsvg,
                      "//svg:g[@id='clickme']",
                      c(svg="http://www.w3.org/2000/svg"))[[1]]
circle <- getNodeSet(gridgarnishsvg,
                     "//svg:circle",
                     c(svg="http://www.w3.org/2000/svg"))[[1]]
devnull <- removePresentation(circle)
cat(saveXML(circleg))


###################################################
### code chunk number 92: gridinteract
###################################################
grid.circle(r=.1, gp=gpar(fill="black"), name="clickme")
grid.garnish("clickme", onmousedown="allwhite()")
grid.script("
  allwhite = function() {
    circle = document.getElementById('clickme.1');
    circle.setAttribute('style', 'fill:white');
  }", name="allwhite")


###################################################
### code chunk number 93: gridsvg.Rnw:1609-1612
###################################################
grid.newpage()
grid.circle(r=.1, gp=gpar(fill="black"), name="clickme")
grid.garnish("clickme", onmousedown="allwhite()")
grid.script("
  allwhite = function() {
    circle = document.getElementById('clickme.1');
    circle.setAttribute('style', 'fill:white');
  }", name="allwhite")
gridToSVG("gridinteract.svg")


###################################################
### code chunk number 94: gridsvg.Rnw:1617-1630
###################################################
gridinteractsvg <- xmlParse("gridinteract.svg")
removeStyle <- function(node) {
    if (is(node, "XMLInternalElementNode")) {
        removePresentation(node)
        children <- xmlChildren(node)
        if (length(children) > 0)
            lapply(children, removeStyle)
    }
    invisible()
}
invisible(lapply(xmlChildren(gridinteractsvg), removeStyle))
cat(breakLongLine(saveXML(gridinteractsvg),
                  "<svg", c("xmlns:xlink", "width"), "xmlns"))


###################################################
### code chunk number 95: threecircles
###################################################
grid.circle(x=1:3/4, r=.1, gp=gpar(fill="black"),
            name="threeCircles")
grid.garnish("threeCircles", 
             onmousedown="alert('ouch')")


###################################################
### code chunk number 96: gridsvg.Rnw:1658-1661
###################################################
grid.newpage()
grid.circle(x=1:3/4, r=.1, gp=gpar(fill="black"),
            name="threeCircles")
grid.garnish("threeCircles", 
             onmousedown="alert('ouch')")
gridToSVG("threeCircles.svg")


###################################################
### code chunk number 97: gridsvg.Rnw:1664-1681
###################################################
threecirclessvg <- xmlParse("threeCircles.svg")
circleg <- getNodeSet(threecirclessvg,
                      "//svg:g[@id='threeCircles']",
                      c(svg="http://www.w3.org/2000/svg"))[[1]]
circle1 <- getNodeSet(threecirclessvg,
                     "//svg:circle[@id='threeCircles.1']",
                     c(svg="http://www.w3.org/2000/svg"))[[1]]
devnull <- removePresentation(circle1)
circle2 <- getNodeSet(threecirclessvg,
                     "//svg:circle[@id='threeCircles.2']",
                     c(svg="http://www.w3.org/2000/svg"))[[1]]
devnull <- removePresentation(circle2)
circle3 <- getNodeSet(threecirclessvg,
                     "//svg:circle[@id='threeCircles.3']",
                     c(svg="http://www.w3.org/2000/svg"))[[1]]
devnull <- removePresentation(circle3)
cat(saveXML(circleg))


###################################################
### code chunk number 98: diffcircles
###################################################
grid.circle(x=1:3/4, r=.1, gp=gpar(fill="black"),
            name="diffCircles")
grid.garnish("diffCircles", 
             onmousedown=c("alert('click me!')",
                           "alert('no, click me!')",
                           "alert('no, no, click me!')"),
             group=FALSE)


###################################################
### code chunk number 99: gridsvg.Rnw:1706-1709
###################################################
grid.newpage()
grid.circle(x=1:3/4, r=.1, gp=gpar(fill="black"),
            name="diffCircles")
grid.garnish("diffCircles", 
             onmousedown=c("alert('click me!')",
                           "alert('no, click me!')",
                           "alert('no, no, click me!')"),
             group=FALSE)
gridToSVG("diffCircles.svg")


###################################################
### code chunk number 100: gridsvg.Rnw:1712-1730
###################################################
diffcirclessvg <- xmlParse("diffCircles.svg")
circleg <- getNodeSet(diffcirclessvg,
                      "//svg:g[@id='diffCircles']",
                      c(svg="http://www.w3.org/2000/svg"))[[1]]
circle1 <- getNodeSet(diffcirclessvg,
                     "//svg:circle[@id='diffCircles.1']",
                     c(svg="http://www.w3.org/2000/svg"))[[1]]
devnull <- removePresentation(circle1)
circle2 <- getNodeSet(diffcirclessvg,
                     "//svg:circle[@id='diffCircles.2']",
                     c(svg="http://www.w3.org/2000/svg"))[[1]]
devnull <- removePresentation(circle2)
circle3 <- getNodeSet(diffcirclessvg,
                     "//svg:circle[@id='diffCircles.3']",
                     c(svg="http://www.w3.org/2000/svg"))[[1]]
devnull <- removePresentation(circle3)
cat(breakLongLine(saveXML(circleg),
                  "<circle", "onmousedown", "id"))


###################################################
### code chunk number 101: boxedtext
###################################################
bt <- grob(label="this is a label", name="bt",
           cl="boxedtext")


###################################################
### code chunk number 102: btgrob
###################################################
btgrob <- function(x) {
    tg <- textGrob(x$label, name="text")
    rg <- rectGrob(width=grobWidth(tg) + unit(2, "mm"), 
                   height=unit(1, "lines"),
                   gp=gpar(col=NA, fill="grey"), name="box")
    gTree(children=gList(rg, tg), name=x$name)
}


###################################################
### code chunk number 103: drawdetails
###################################################
drawDetails.boxedtext <- function(x, ...) {
    grid.draw(btgrob(x))
}


###################################################
### code chunk number 104: editsrc
###################################################
grid.draw(bt)
grid.edit("bt", label="New label!")


###################################################
### code chunk number 105: edit
###################################################
pdf("gridsvg-edit-%d.pdf", width=2, height=1, onefile=FALSE)
grid.draw(bt)
grid.edit("bt", label="New label!")
dev.off()


###################################################
### code chunk number 106: primtodev
###################################################
primToDev.boxedtext <- function(x, ...) {
    primToDev(btgrob(x), ...)
}


###################################################
### code chunk number 107: gridsvg.Rnw:1816-1819
###################################################
grid.newpage()
grid.draw(bt)
gridToSVG("boxedtext.svg")


###################################################
### code chunk number 108: gridsvg.Rnw:1822-1835
###################################################
boxedtextsvg <- xmlParse("boxedtext.svg")
btg <- getNodeSet(boxedtextsvg,
                      "//svg:g[@id='bt']",
                      c(svg="http://www.w3.org/2000/svg"))[[1]]
text <- getNodeSet(boxedtextsvg,
                   "//svg:text",
                   c(svg="http://www.w3.org/2000/svg"))[[1]]
devnull <- removePresentation(text)
rect <- getNodeSet(boxedtextsvg,
                   "//svg:rect",
                   c(svg="http://www.w3.org/2000/svg"))[[1]]
devnull <- removePresentation(rect)
cat(saveXML(btg))


###################################################
### code chunk number 109: gridsvg.Rnw:1864-1874
###################################################
# Just enough code to get some sample output
# FULL code in Examples/Wild/

modes <- c("walk", "car", "bus", "bike", "other")
travel <- factor(rep(modes,
                     c(7349, 8992, 6486, 1156, 263+311+384)))
# Take many samples from the pop and tabulate them
n <- 100
sn <- 100
samples <- lapply(1:n, function(i) { table(sample(travel, sn)) })


###################################################
### code chunk number 110: gridsvg.Rnw:1877-1878
###################################################
samples[1:3]


###################################################
### code chunk number 111: barchart
###################################################
boxWidth <- unit(2, "cm")
barchart(samples[[1]],
         col=rgb(0,0,1,.2),
         ylim=c(0, max(sapply(samples, max))),
         horizontal=FALSE,
         box.width=boxWidth)


###################################################
### code chunk number 112: gridsvg.Rnw:1910-1914 (eval = FALSE)
###################################################
## time <- 10
## grid.animate("plot_01.barchart.rect.panel.1.1",
##              height=do.call("rbind", samples),
##              duration=time, interpolate="discrete")


###################################################
### code chunk number 113: footprintsrc (eval = FALSE)
###################################################
## trellis.focus("panel", 1, 1)
## count <- 1
## samplefun <- function(samp) {
##     grid.segments(unit(1:5, "native") - 0.5*boxWidth,
##                   unit(samp, "native"), 
##                   unit(1:5, "native") + 0.5*boxWidth,
##                   unit(samp, "native"),
##                   gp=gpar(lwd=2, col=rgb(0,0,1,.2)),
##                   name=paste("sample.line", count, sep="."))
##     count <<- count + 1
## }    
## lapply(samples, samplefun)
## trellis.unfocus()


###################################################
### code chunk number 114: footprints
###################################################
pdf("gridsvg-footprints-%d.pdf", onefile=FALSE)
boxWidth <- unit(2, "cm")
barchart(samples[[1]],
         col=rgb(0,0,1,.2),
         ylim=c(0, max(sapply(samples, max))),
         horizontal=FALSE,
         box.width=boxWidth)
trellis.focus("panel", 1, 1)
count <- 1
samplefun <- function(samp) {
    grid.segments(unit(1:5, "native") - 0.5*boxWidth,
                  unit(samp, "native"), 
                  unit(1:5, "native") + 0.5*boxWidth,
                  unit(samp, "native"),
                  gp=gpar(lwd=2, col=rgb(0,0,1,.2)),
                  name=paste("sample.line", count, sep="."))
    count <<- count + 1
}    
lapply(samples, samplefun)
trellis.unfocus()
dev.off()


###################################################
### code chunk number 115: animatefootprints (eval = FALSE)
###################################################
## for (i in 1:n) {
##     grid.garnish(paste("sample.line", i, sep="."),
##                  visibility="hidden")
##     grid.animate(paste("sample.line", i, sep="."),
##                  visibility=c("hidden", "visible"),
##                  group=TRUE,
##                  begin=i/n*time,
##                  duration=.01)
## }


###################################################
### code chunk number 116: gridsvg.Rnw:1993-1994
###################################################
library("ggplot2")


###################################################
### code chunk number 117: qplotsrc
###################################################
qplot(disp, mpg, data=mtcars) + facet_wrap(~ cyl)


###################################################
### code chunk number 118: qplot
###################################################
print(
qplot(disp, mpg, data=mtcars) + facet_wrap(~ cyl)
)


###################################################
### code chunk number 119: gridsvg.Rnw:2020-2021 (eval = FALSE)
###################################################
## grid.ls()


###################################################
### code chunk number 120: gridsvg.Rnw:2024-2033
###################################################
print(
qplot(disp, mpg, data=mtcars) + facet_wrap(~ cyl)
)
x <- grid.ls()
y <- lapply(x, "[", 1:5)
class(y) <- "flatGridListing"
# Capture the display list so can reuse it later
DL <- grid:::grid.Call("L_getDisplayList")
DLi <- grid:::grid.Call("L_getDLindex")


###################################################
### code chunk number 121: gridsvg.Rnw:2036-2037
###################################################
y


###################################################
### code chunk number 122: gridlsgrobs (eval = FALSE)
###################################################
## grobs <- grid.ls()
## names <- grobs$name[grobs$type == "grobListing"]


###################################################
### code chunk number 123: ggplotgarnish (eval = FALSE)
###################################################
## for (i in unique(names)) {
##     grid.garnish(i, 
##                  onmouseover=paste("showTooltip(evt, '", i, "')"),
##                  onmouseout="hideTooltip()")
## }


###################################################
### code chunk number 124: qplotbrowser (eval = FALSE)
###################################################
## grid.script(filename="tooltip.js")
## gridToSVG("qplotbrowser.svg")


###################################################
### code chunk number 125: gridsvg.Rnw:2072-2081
###################################################
# Restore exact display list 
# (otherwise auto-generated grob names are different)
grid.newpage()
devnull <- grid:::grid.Call("L_setDisplayList", DL)
devnull <- grid:::grid.Call("L_setDLindex", as.integer(DLi))
grobs <- grid.ls()
names <- grobs$name[grobs$type == "grobListing"]
names <- names[names != "NULL"]
for (i in unique(names)) {
    grid.garnish(i, 
                 onmouseover=paste("showTooltip(evt, '", i, "')"),
                 onmouseout="hideTooltip()")
}
grid.script(filename="tooltip.js")
gridToSVG("qplotbrowser.svg")


###################################################
### code chunk number 126: design
###################################################
textBox <- function(label, x, y) {
    grid.roundrect(x, y, height=unit(1, "lines"),
              width=stringWidth(label) + unit(2, "mm"),
              name=label,
              gp=gpar(fill="white"))
    grid.text(label, x, y)
}
lineBetween <- function(from, to, afrom, ato) {
    grid.segments(grobX(from, afrom), grobY(from, afrom),
                  grobX(to, ato), grobY(to, ato),
                  arrow=arrow(length=unit(3, "mm"), angle=10,
                    type="closed"),
                  gp=gpar(fill="black"))
}
grid.newpage()
grid.roundrect(.1, .5, width=.4, height=.4,
               just="left",
               gp=gpar(col=NA, fill="grey80"))

textBox("graphics", .2, .6)
textBox("grid", .2, .4)

textBox("grDevices", .4, .5)
lineBetween("graphics", "grDevices", 0, 180)
lineBetween("grid", "grDevices", 0, 180)

nright <- 4
maxright <- 50 
minright <- -50
t <- seq(minright, maxright, length.out=nright)
x <- .5 + cos(t/180*pi)*.3
y <- .5 + sin(t/180*pi)*.4
right <- c("PDF", "PNG", "SVG", "RSVGTipsDevice")
for (i in 1:nright) {
    textBox(right[nright - i + 1], x[i], y[i])
    lineBetween("grDevices", right[nright - i + 1], 0, 
                switch(as.character(i), "1"=90, 180))
}

textBox("gridSVG", .4, .2)
lineBetween("grid", "gridSVG", 0, 90)


###################################################
### code chunk number 127: gridsymbolssrc (eval = FALSE)
###################################################
## grid.points(1:3/4, 1:3/4, pch=10, name="points")


###################################################
### code chunk number 128: gridsymbols
###################################################
pushViewport(viewport(layout=grid.layout(1, 3)))
pushViewport(viewport(layout.pos.col=1))
grid.rect(width=.9, height=.9)
grid.points(1:3/4, 1:3/4, pch=10)
popViewport()
pushViewport(viewport(layout.pos.col=2))
grid.rect(width=.9, height=.9)
grid.rect(y=.95, height=unit(1.5, "lines"), just="top", width=.9,
          gp=gpar(fill="black"))
grid.text("grid display list",
          y=unit(.95, "npc") - unit(.75, "lines"),
          gp=gpar(col="white"))
grid.text("\"points\" grob",
          y=unit(.95, "npc") - unit(2.5, "lines"), just="top")
popViewport()
pushViewport(viewport(layout.pos.col=3))
grid.rect(width=.9, height=.9)
grid.rect(y=.95, height=unit(1.5, "lines"), just="top", width=.9,
          gp=gpar(fill="black"))
grid.text("R graphics engine",
          y=unit(.95, "npc") - unit(.75, "lines"),
          gp=gpar(col="white"))
grid.text("circle\nline\nline\ncircle\nline\nline\ncircle\nline\nline",
          y=unit(.95, "npc") - unit(2.5, "lines"), just="top")


###################################################
### code chunk number 129: gridsvg.Rnw:2295-2298
###################################################
svg("gridsceneCairo.svg", width=2, height=2)
topvp <- viewport(y=1, just="top", name="topvp",
                  height=unit(1, "lines"))
botvp <- viewport(y=0, just="bottom", name="botvp",
                  height=unit(1, "npc") - unit(1, "lines"))
grid.rect(gp=gpar(fill="grey"), vp=topvp, name="toprect")
grid.rect(vp=botvp, name="botrect")
dev.off()


###################################################
### code chunk number 130: gridsvg.Rnw:2302-2314
###################################################
gridscenesvg <- xmlParse("gridsceneCairo.svg")
removeStyle <- function(node) {
    removeAttributes(node, .attrs="style")
    children <- xmlChildren(node)
    if (length(children) > 0)
        lapply(children, removeStyle)
    invisible()
}
invisible(lapply(xmlChildren(gridscenesvg), removeStyle))
cat(breakLongLine(breakLongLine(saveXML(gridscenesvg),
                                "<svg", c("xmlns:xlink", "width"), "xmlns"),
                  "<path", "transform", "d"))


###################################################
### code chunk number 131: gridsvg.Rnw:2413-2418
###################################################
df <- data.frame(time=as.numeric(time(Nile)), 
                 flow=as.numeric(Nile))
thePlot <- ggplot(df, aes(x=time, y=flow)) + 
           geom_line() 
botPlot <- thePlot 


###################################################
### code chunk number 132: gridsvg.Rnw:2421-2428
###################################################
# Fine tune lower plot:
# invisibilize y-axis label, thin y-axis scale, and remove x-axis
botPlot <- thePlot +
           scale_y_continuous(breaks=c(600, 1200)) +
           opts(plot.background=theme_rect(colour="transparent"),
                axis.title.y=theme_text(colour="white", size=6),
                axis.title.x=theme_blank())


###################################################
### code chunk number 133: gridsvg.Rnw:2435-2445
###################################################
doplot <- function() {
    pushViewport(viewport(y=1, height=.8, just="top", 
                          name="topvp"))
    print(thePlot, newpage=FALSE)
    upViewport()
    pushViewport(viewport(y=0, height=.25, just="bottom", 
                          name="bottomvp"))
    print(botPlot, newpage=FALSE)
    upViewport()
}


###################################################
### code chunk number 134: gridsvg.Rnw:2449-2453
###################################################
pdf(width=4, height=4)
doplot()
gridToSVG("normalplot.svg")
dev.off()


###################################################
### code chunk number 135: gridsvg.Rnw:2460-2464
###################################################
pdf(width=12, height=4)
doplot()
gridToSVG("wideplot.svg")
dev.off()


###################################################
### code chunk number 136: gridsvg.Rnw:2472-2473
###################################################
library("XML")


###################################################
### code chunk number 137: gridsvg.Rnw:2478-2480
###################################################
normalSVG <- xmlParse("normalplot.svg")
wideSVG <- xmlParse("wideplot.svg")


###################################################
### code chunk number 138: gridsvg.Rnw:2488-2492
###################################################
normalPlotSVG <- 
    getNodeSet(normalSVG,
               "//svg:g[@id='panel-3-3.1']",
               c(svg="http://www.w3.org/2000/svg"))[[1]]


###################################################
### code chunk number 139: gridsvg.Rnw:2498-2502
###################################################
widePlotSVG <- 
    getNodeSet(wideSVG,
               "//svg:g[@id='panel-3-3.1']/svg:g[@id='panel-3-3']",
               c(svg="http://www.w3.org/2000/svg"))[[1]]


###################################################
### code chunk number 140: gridsvg.Rnw:2505-2533
###################################################
# To set clip attribute for axis viewport,
# need the x, y, width, height from background rect for panel-3-3
# (which is first <rect> below panel-3-3)
# BEFORE we replace that with the one from fancyWide.svg!
panelBg  <- getNodeSet(normalPlotSVG,
                       ".//svg:rect",
                       c(svg="http://www.w3.org/2000/svg"))[[1]]
# Do same thing for x-axis
normalAxisSVG <- getNodeSet(normalSVG,
                            "//svg:g[@id='axis_h-5-3.1']",
                            c(svg="http://www.w3.org/2000/svg"))[[1]]
wideAxisSVG <-
    getNodeSet(wideSVG,
               "//svg:g[@id='axis_h-5-3.1']/svg:g[@id='axis_h-5-3']",
               c(svg="http://www.w3.org/2000/svg"))[[1]]
removeChildren(normalAxisSVG, "g")
addChildren(normalAxisSVG, wideAxisSVG)
# Set a clip region for the x-axis on the top plot
axisClipRectAttrs <- xmlAttrs(panelBg)[c("x", "y", "width", "height")]
axisClipRectAttrs["height"] <- axisClipRectAttrs["y"]
axisClipRectAttrs["y"] <- 0
addChildren(normalAxisSVG,
            newXMLNode("clipPath",
                       newXMLNode("rect",
                                  attrs=axisClipRectAttrs),
                       attrs=c(id="axis_h-5-3.1-clip")))
addAttributes(normalAxisSVG,
              "clip-path"="url(#axis_h-5-3.1-clip)")


###################################################
### code chunk number 141: gridsvg.Rnw:2542-2545
###################################################
removeChildren(normalPlotSVG, "g")
addChildren(normalPlotSVG, widePlotSVG)
saveXML(normalSVG, file="customplot.svg")


###################################################
### code chunk number 142: gridsvg.Rnw:2548-2551
###################################################
system("inkscape --export-png=normalplotsvg.png --export-dpi=300 normalplot.svg")
system("inkscape --export-png=wideplotsvg.png --export-dpi=300 wideplot.svg")
system("inkscape --export-png=customplotsvg.png --export-dpi=300 customplot.svg")


