Provides a number of user-level functions to work with "grid" graphics, notably to arrange multiple grid-based plots on a page, and draw tables.
提供一些用戶級別的函數(shù)來處理“網(wǎng)格”圖形诀蓉,特別是在頁面上安排多個基于網(wǎng)格的繪圖沽瞭,并繪制表格漓库。
基礎(chǔ)使用
basic usage
In this example we mix a few grobs and plots.
library(gridExtra)
library(grid)
library(ggplot2)
library(lattice)
p <- qplot(1,1)
p2 <- xyplot(1~1) ##lattice包
r <- rectGrob(gp = gpar(fill = "grey90")) ##rectGrob
t <- textGrob("text")
grid.arrange(t,p,p2,ncol = 2)
Title and/or annotations
gs <- lapply(1:9, function(ii)
grobTree(rectGrob(gp = gpar(fill = ii,alpha = 0.5)),textGrob(ii)))
# gs
grid.arrange(grobs = gs,ncol = 4,top = "top label",bottom = "bottom\nlabel",left = "left label",right = "right label")
grid.rect(gp = gpar(fill = NA)) ##外邊框
Complex layouts
復(fù)雜布局
We can provide a matrix defining the layout
使用矩陣定義一個布局
lay <- rbind(c(1,1,1,2,3),
c(1,1,1,4,5),
c(6,7,8,9,9))
grid.arrange(grobs = gs,layout_matrix = lay)
The layout itself may contain holes,but note that for any given grob index the region must be simply connected(no hole)
hlay <- rbind(c(1,1,NA,2,3),
c(1,1,NA,4,NA),
c(NA,7,8,9,NA))
select_grobs <- function(lay) {
id <- unique(c(t(lay)))
id[!is.na(id)]
}
grid.arrange(grobs=gs[select_grobs(hlay)], layout_matrix=hlay)
All cells are of equal size by default, but users may pass explicity widths and/or heights in any valid grid units, or as relative numbers (interpreted as null)
grid.arrange(grobs = gs[1:3],ncol = 2,widths = 1:2,heights = unit(c(1,10),c("in","mm")))
Nested layouts with arrangeGrob
The grid.arrange()
function draws on the device;for more complex layouts,we may want to store the gtable and combine it with other objects,e.g.forming nested layouts.To this end,usearrangeGrob()
.
g1 <- arrangeGrob(grobs = gs,layout_matrix = t(lay))
g2 <- arrangeGrob(grobs = gs,layout_matrix = lay)
grid.arrange(g1,g2,ncol = 2)
Multiple pages output
Finally, we may want to place grobs on multiple pages; the marrangeGrob() function provides a convenient interface for this, also compatible with ggsave().
set.seed(123)
pl <- lapply(1:11,function(.x)
qplot(1:10,rnorm(10),main = paste("plot",.x)))
ml <- marrangeGrob(pl,nrow = 2,ncol = 2)
ml
Regular polygons and ellipses in grid graphics
多邊形和橢圓
N <- 5
xy <- polygon_regular(N)*2
# draw multiple polygons
g <- ngonGrob(unit(xy[,1],"cm") + unit(0.5,"npc"),
unit(xy[,2],"cm") + unit(0.5,"npc"),
n=seq_len(N)+2, gp=gpar(fill=1:N))
grid.newpage()
grid.draw(g)
Rotated and stetched polygons
g2 <- ngonGrob(unit(xy[,1],"cm") + unit(0.5,"npc"),
unit(xy[,2],"cm") + unit(0.5,"npc"),
n=seq_len(N)+2, ar=seq_len(N),
phase=0, angle=pi/(seq_len(N)+2),
size=1:N+5, gp=gpar(fill=1:N))
grid.newpage()
grid.draw(g2)
Ellipses
g3 <- ellipseGrob(unit(xy[,1],"cm") + unit(0.5,"npc"),
unit(xy[,2],"cm") + unit(0.5,"npc"),
angle=-2*seq(0,N-1)*pi/N+pi/2,
size=5, ar=3, gp=gpar(fill=1:N))
grid.newpage()
grid.draw(g3)