首页 文章

格子:一个窗口中有多个图?

提问于
浏览
58

我试图通过设置 par(mfrow=c(2,1)) 使用 levelplot 在一个窗口中放置多个点阵图,但似乎忽略了这一点 .

lattice 中是否有用于设置多个图的特定功能?

3 回答

  • 8

    'lattice'包构建在网格包上,并在加载'lattice'时附加其命名空间 . 但是,为了使用 grid.layout 函数,您需要显式地 load() pkg :: grid . 另一个可能更容易的选择是pkg :: gridExtra中的 grid.arrange 函数:

    install.packages("gridExtra")
     require(gridExtra) # also loads grid
     require(lattice)
     x <- seq(pi/4, 5 * pi, length.out = 100)
     y <- seq(pi/4, 5 * pi, length.out = 100)
     r <- as.vector(sqrt(outer(x^2, y^2, "+")))
    
     grid <- expand.grid(x=x, y=y)
     grid$z <- cos(r^2) * exp(-r/(pi^3))
     plot1 <- levelplot(z~x*y, grid, cuts = 50, scales=list(log="e"), xlab="",
               ylab="", main="Weird Function", sub="with log scales",
               colorkey = FALSE, region = TRUE)
    
     plot2 <- levelplot(z~x*y, grid, cuts = 50, scales=list(log="e"), xlab="",
               ylab="", main="Weird Function", sub="with log scales",
               colorkey = FALSE, region = TRUE)
     grid.arrange(plot1,plot2, ncol=2)
    

    enter image description here

  • 65

    莱迪思软件包经常(但不总是)忽略par命令,因此我在绘制w / Lattice时避免使用它 .

    要在单个页面上放置多个点阵图:

    • create (但不要绘制)格子/格子 plot objects ,然后

    • 为每个情节调用 print 一次

    每次打印调用

    • ,传入(i)图的参数; (ii) more ,设置为TRUE,仅传递给初始调用print,以及(iii) pos ,它给出了每个绘图在页面上的位置,指定为xy坐标对,用于绘图的左下角角和右上角 - 分别是一个带有四个数字的向量 .

    更容易展示而不是告诉:

    data(AirPassengers)     # a dataset supplied with base R
    AP = AirPassengers      # re-bind to save some typing
    
    # split the AP data set into two pieces 
    # so that we have unique data for each of the two plots
    w1 = window(AP, start=c(1949, 1), end=c(1952, 1))
    w2 = window(AP, start=c(1952, 1), end=c(1960, 12))
    
    px1 = xyplot(w1)
    px2 = xyplot(w2)
    
    # arrange the two plots vertically
    print(px1, position=c(0, .6, 1, 1), more=TRUE)
    print(px2, position=c(0, 0, 1, .4))
    
  • 41

    一旦你阅读 ?print.trellis ,这很简单 . 特别感兴趣的是 split 参数 . 乍一看似乎很复杂,但一旦你理解了它的意义,它就会非常简单 . 从文档:

    split:4个整数的向量,c(x,y,nx,ny),表示将当前绘图定位在nx图的nx常规数组中的x,y位置 . (注意:这来自左上角)

    您可以在 example(print.trellis) 上看到几个实现,但这是我更喜欢的一个:

    library(lattice)
    
    # Data
    w <- as.matrix(dist(Loblolly))
    x <- as.matrix(dist(HairEyeColor))
    y <- as.matrix(dist(rock))
    z <- as.matrix(dist(women))
    
    # Plot assignments
    pw <- levelplot(w, scales = list(draw = FALSE))  # "scales..." removes axes
    px <- levelplot(x, scales = list(draw = FALSE))
    py <- levelplot(y, scales = list(draw = FALSE))
    pz <- levelplot(z, scales = list(draw = FALSE))
    
    # Plot prints
    print(pw, split = c(1, 1, 2, 2), more = TRUE)
    print(px, split = c(2, 1, 2, 2), more = TRUE)
    print(py, split = c(1, 2, 2, 2), more = TRUE)
    print(pz, split = c(2, 2, 2, 2), more = FALSE)  # more = FALSE is redundant
    

    上面的代码给出了这个数字:
    levelplots

    如您所见, split 有四个参数 . 最后两个参考框架的大小(类似于 mfrow 的大小),而前两个参数将您的图形定位到 nx by ny 框架 .

相关问题