首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >带R的多页SVG

带R的多页SVG
EN

Stack Overflow用户
提问于 2011-09-26 19:08:01
回答 1查看 674关注 0票数 2

当在lattice::xyplottrellis.device中使用layout时,你可以在一个PDF中获得几个页面:

代码语言:javascript
代码运行次数:0
运行
复制
trellis.device(pdf, file="myfile.pdf")
data(mtcars)
xyplot(hp~mpg|gear, data=mtcars, layout=c(1, 1))
dev.off()

我想使用相同的方法来获得一个multi-page SVG。我尝试过cairo::svg,包gridSVGSVGAnnotationRSVGTipsDevice都没有成功:只保存了trellis对象的最后一页。

有没有使用R代码的解决方案?

谢谢!

EN

回答 1

Stack Overflow用户

发布于 2011-11-13 02:20:04

我最终决定直接请教grid和gridSVG的创建者Paul Murrell。他亲切地提供了一些很好的建议和代码,用类似于@mbq的建议的方法完全解决了这个问题。我修改了他的代码,编写了这个函数:

代码语言:javascript
代码运行次数:0
运行
复制
library(gridSVG)
library(XML)

animateTrellis <- function(object, file='animatedSVG.svg', 
                           duration=.1, step=2, show=TRUE){
  nLayers <- dim(object)
  stopifnot(nLayers>1)
  for (i in seq_len(nLayers)){
    p <- object[i]
    label <- p$condlevels[[1]][i]
    ##Create intermediate SVG files
    g <- grid.grabExpr(print(p, prefix=label),
                       name=label)
    if (i==1){ ## First frame
      ga <- animateGrob(g, group=TRUE,
                        visibility="hidden",
                        duration=duration, begin=step)
    } else if (i==nLayers){ ##Last Frame
      gg <- garnishGrob(g, visibility='hidden')
      ga <- animateGrob(gg, group=TRUE,
                        visibility="visible",
                        duration=duration, begin=step*(i-1))
    } else { ##any frame
      gg <- garnishGrob(g, visibility='hidden')
      gaV <- animateGrob(gg, group=TRUE,
                         visibility="visible",
                         duration=duration, begin=step*(i-1))
      ga <- animateGrob(gaV, group=TRUE,
                        visibility="hidden",
                        duration=duration, begin=step*i)
    }
    grid.newpage()
    grid.draw(ga)
    fich <- tempfile(fileext='.svg')
    gridToSVG(fich)

    ## Combine all
    if (i==1) {
      svgTop <- xmlParse(fich)
      nodeTop <- getNodeSet(svgTop,
                            "//svg:g[@id='gridSVG']",
                            c(svg="http://www.w3.org/2000/svg"))[[1]]
    } else {
      svgChildren <- xmlParse(fich)
      node <- getNodeSet(svgChildren,
                         "//svg:g[@id='gridSVG']/*",
                         c(svg="http://www.w3.org/2000/svg"))
      addChildren(nodeTop, node)
    }
    unlink(fich)
  }
  saveXML(svgTop, file=file)
  dev.off()
  if (show) browseURL(file)
  invisible(svgTop)
}

然后我可以生成带有动画的SVG文件:

代码语言:javascript
代码运行次数:0
运行
复制
p <- xyplot(Sepal.Length~Petal.Length|Species, data=iris, layout=c(1, 1))
animateTrellis(p, file='iris.svg')
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7554162

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档