gridExtra/ 0000755 0001762 0000144 00000000000 13154773270 012214 5 ustar ligges users gridExtra/TODO 0000644 0001762 0000144 00000000543 13010764171 012675 0 ustar ligges users
NEW FEATURES
* basic plots (image, plot, É) in grid, using scales and guide packages of Hadley W.
* matrix plot
* clone and export linearised versions of all basic grid grobs, i.e. with full list of arguments (no gp) accessible to vectorisation
* explore the idea of a new unit system based on complex numbers, one part for physical vs relative units gridExtra/inst/ 0000755 0001762 0000144 00000000000 13154617431 013165 5 ustar ligges users gridExtra/inst/tests/ 0000755 0001762 0000144 00000000000 13010764171 014322 5 ustar ligges users gridExtra/inst/tests/testthat.r 0000644 0001762 0000144 00000000076 13010764171 016350 0 ustar ligges users library(gridExtra)
library(testthat)
test_check("gridExtra")
gridExtra/inst/tests/testthat/ 0000755 0001762 0000144 00000000000 13154773270 016173 5 ustar ligges users gridExtra/inst/tests/testthat/test-arrangeGrob.R 0000644 0001762 0000144 00000003742 13010764171 021521 0 ustar ligges users library(gridExtra)
library(testthat)
library(grid)
r <- rectGrob(gp=gpar(fill="grey90"))
context("Checking layout")
test_that("nrow/ncol define a layout", {
expect_that(dim(arrangeGrob(r,r,r)), equals(c(3,1)))
expect_that(dim(arrangeGrob(r,r,r, nrow=2)), equals(c(2,2)))
expect_that(dim(arrangeGrob(r,r,r, ncol=2)), equals(c(2,2)))
expect_that(dim(arrangeGrob(r,r,r, ncol=4)), equals(c(1,4)))
expect_that(dim(arrangeGrob(r,r,r, nrow=4)), equals(c(4,1)))
expect_that(dim(arrangeGrob(r,r,r, nrow=1)), equals(c(1,3)))
expect_that(dim(arrangeGrob(r,r,r, ncol=1)), equals(c(3,1)))
expect_that(dim(arrangeGrob(r,r,r, ncol=2,nrow=2)), equals(c(2,2)))
expect_that(dim(arrangeGrob(r,r,r, ncol=3,nrow=4)), equals(c(4,3)))
expect_error(arrangeGrob(r,r,r, ncol=1,nrow=1))
})
test_that("widths/heights define a layout", {
expect_that(dim(arrangeGrob(r,r,r, widths=1)), equals(c(3,1)))
expect_that(dim(arrangeGrob(r,r,r, heights=1)), equals(c(1,3)))
expect_that(dim(arrangeGrob(r,r,r, widths=1:3)), equals(c(1,3)))
expect_that(dim(arrangeGrob(r,r,r, widths=1:5)), equals(c(1,5)))
expect_that(dim(arrangeGrob(r,r,r, heights=1:3)), equals(c(3,1)))
expect_that(dim(arrangeGrob(r,r,r, heights=1:5)), equals(c(5,1)))
expect_that(dim(arrangeGrob(r,r,r, widths=1:5)), equals(c(1,5)))
expect_that(dim(arrangeGrob(r,r,r, widths=1:5, heights=1:5)),
equals(c(5,5)))
expect_error(arrangeGrob(r,r,r, widths=1, heights=1))
})
test_that("combinations of nrow/ncol and widths/heights define a layout", {
expect_that(dim(arrangeGrob(r,r,r, nrow=2, widths=1:3)),
equals(c(2,3)))
expect_that(dim(arrangeGrob(r,r,r, ncol=2, heights=1:3)),
equals(c(3,2)))
expect_that(dim(arrangeGrob(r,r,r, ncol=2, widths=1:2)),
equals(c(2,2)))
expect_that(dim(arrangeGrob(r,r,r, nrow=2, heights=1:2)),
equals(c(2,2)))
expect_error(arrangeGrob(r,r,r, ncol=2, widths=1:3))
expect_error(arrangeGrob(r,r,r, nrow=2, heights=1:3))
})
gridExtra/inst/tests/testthat/test-tableGrob.R 0000644 0001762 0000144 00000000647 13010764171 021172 0 ustar ligges users library(gridExtra)
library(testthat)
library(grid)
m <- iris[1:4, 1:3]
context("Checking tableGrob layout")
test_that("tableGrob has the correct size", {
expect_that(dim(tableGrob(m)), equals(c(5,4)))
expect_that(dim(tableGrob(m, rows = NULL)), equals(c(5,3)))
expect_that(dim(tableGrob(m, cols = NULL)), equals(c(4,4)))
expect_that(dim(tableGrob(m, rows = NULL, cols = NULL)),
equals(c(4,3)))
})
gridExtra/inst/NEWS.md 0000644 0001762 0000144 00000002747 13152367440 014275 0 ustar ligges users # gridExtra 2.3.0 (2017-09-01)
## Misc. cleanup for CRAN release
* renamed `cbind/rbind` functions copied from gtable to `cbind_gtable` and `rbind_gtable` to avoid issues with generic method (different signature)
* more consistency in gtable-related functions
# gridExtra 2.2.0 (2016-02-27)
## NEW FEATURES
* added padding argument to table themes
* simplified a few theme arguments
## BUG FIX
* recycling logic was flawed for aesthetics in table cells
# gridExtra 2.1.0 (2015-07-27)
## DOCUMENTATION
* expanded vignettes
* wiki page features a FAQ section
## NEW FEATURES
* added join function from gtable (with fix)
* global size and font parameters more accessible in themes
* added str.gtable method
## BUG FIX
* str.default was causing issues with gtables
# gridExtra 2.0.0 (2015-07-11)
* removed experimental grobs and functions not widely used (they can be found at https://github.com/baptiste/gridextra if needed)
* arrangeGrob/grid.arrange is now based on gtable
* tableGrob/grid.table is now based on gtable
# gridExtra 1.0.0 (2014-10-05)
## CLEANUP
* several buggy functions removed
# gridExtra 0.9.1 (2012-08-09)
## FIX
* small compatibility issue of arrangeGrob with new class of ggplot2
# gridExtra 0.9 (2012-01-06)
## FIX
* dependencies in examples, imports and exports
## NEW
* multipage output and ggsave support for grid.arrange
# gridExtra 0.8.5 (2011-10-26)
## FIX
* removed LazyLoad, deprecated in R>=2.14
## NEW
* stextGrob text with a background gridExtra/inst/doc/ 0000755 0001762 0000144 00000000000 13154617417 013736 5 ustar ligges users gridExtra/inst/doc/tableGrob.R 0000644 0001762 0000144 00000015371 13154617416 015770 0 ustar ligges users ## ----setup, echo=FALSE, results='hide'-----------------------------------
library(knitr)
opts_chunk$set(message=FALSE, fig.width=4, fig.height=2)
## ----basic---------------------------------------------------------------
library(gridExtra)
library(grid)
d <- head(iris[,1:3])
grid.table(d)
## ----annotations, fig.height=3-------------------------------------------
d[2,3] <- "this is very wwwwwide"
d[1,2] <- "this\nis\ntall"
colnames(d) <- c("alpha*integral(xdx,a,infinity)",
"this text\nis high", 'alpha/beta')
tt <- ttheme_default(colhead=list(fg_params = list(parse=TRUE)))
grid.table(d, theme=tt)
## ----theme, fig.width=8--------------------------------------------------
tt1 <- ttheme_default()
tt2 <- ttheme_minimal()
tt3 <- ttheme_minimal(
core=list(bg_params = list(fill = blues9[1:4], col=NA),
fg_params=list(fontface=3)),
colhead=list(fg_params=list(col="navyblue", fontface=4L)),
rowhead=list(fg_params=list(col="orange", fontface=3L)))
grid.arrange(
tableGrob(iris[1:4, 1:2], theme=tt1),
tableGrob(iris[1:4, 1:2], theme=tt2),
tableGrob(iris[1:4, 1:2], theme=tt3),
nrow=1)
## ----recycling-----------------------------------------------------------
t1 <- ttheme_default(core=list(
fg_params=list(fontface=c(rep("plain", 4), "bold.italic")),
bg_params = list(fill=c(rep(c("grey95", "grey90"),
length.out=4), "#6BAED6"),
alpha = rep(c(1,0.5), each=5))
))
grid.table(iris[1:5, 1:3], theme = t1)
## ----justify, fig.width=8------------------------------------------------
tt1 <- ttheme_default()
tt2 <- ttheme_default(core=list(fg_params=list(hjust=1, x=0.9)),
rowhead=list(fg_params=list(hjust=1, x=0.95)))
tt3 <- ttheme_default(core=list(fg_params=list(hjust=0, x=0.1)),
rowhead=list(fg_params=list(hjust=0, x=0)))
grid.arrange(
tableGrob(mtcars[1:4, 1:2], theme=tt1),
tableGrob(mtcars[1:4, 1:2], theme=tt2),
tableGrob(mtcars[1:4, 1:2], theme=tt3),
nrow=1)
## ----sizes, fig.width=8--------------------------------------------------
g <- g2 <- tableGrob(iris[1:4, 1:3], cols = NULL, rows=NULL)
g2$widths <- unit(rep(1/ncol(g2), ncol(g2)), "npc")
grid.arrange(rectGrob(), rectGrob(), nrow=1)
grid.arrange(g, g2, nrow=1, newpage = FALSE)
## ----align, fig.width=6, fig.height=3------------------------------------
d1 <- PlantGrowth[1:3,1, drop=FALSE]
d2 <- PlantGrowth[1:2,1:2]
g1 <- tableGrob(d1)
g2 <- tableGrob(d2)
haligned <- gtable_combine(g1,g2, along=1)
valigned <- gtable_combine(g1,g2, along=2)
grid.newpage()
grid.arrange(haligned, valigned, ncol=2)
## ----numberingDemo1------------------------------------------------------
library(gtable)
g <- tableGrob(iris[1:4, 1:3], rows = NULL)
g <- gtable_add_grob(g,
grobs = rectGrob(gp = gpar(fill = NA, lwd = 2)),
t = 2, b = nrow(g), l = 1, r = ncol(g))
g <- gtable_add_grob(g,
grobs = rectGrob(gp = gpar(fill = NA, lwd = 2)),
t = 1, l = 1, r = ncol(g))
grid.draw(g)
## ----numberingDemo2------------------------------------------------------
g <- tableGrob(iris[1:4, 1:3])
g <- gtable_add_grob(g,
grobs = rectGrob(gp = gpar(fill = NA, lwd = 2)),
t = 2, b = nrow(g), l = 1, r = ncol(g))
g <- gtable_add_grob(g,
grobs = rectGrob(gp = gpar(fill = NA, lwd = 2)),
t = 1, l = 1, r = ncol(g))
grid.draw(g)
## ----segments1-----------------------------------------------------------
g <- tableGrob(iris[1:4, 1:3])
g <- gtable_add_grob(g,
grobs = segmentsGrob( # line across the bottom
x0 = unit(0,"npc"),
y0 = unit(0,"npc"),
x1 = unit(1,"npc"),
y1 = unit(0,"npc"),
gp = gpar(lwd = 2.0)),
t = 3, b = 3, l = 3, r = 3)
grid.draw(g)
## ----segments2-----------------------------------------------------------
g <- tableGrob(iris[1:4, 1:3])
g <- gtable_add_grob(g,
grobs = segmentsGrob( # line across the bottom
x0 = unit(0,"npc"),
y0 = unit(0,"npc"),
x1 = unit(0,"npc"),
y1 = unit(1,"npc"),
gp = gpar(lwd = 2.0)),
t = 3, b = 3, l = 3, r = 3)
grid.draw(g)
## ----segments3-----------------------------------------------------------
g <- tableGrob(iris[1:4, 1:3])
g <- gtable_add_grob(g,
grobs = grobTree(
segmentsGrob( # diagonal line ul -> lr
x0 = unit(0,"npc"),
y0 = unit(1,"npc"),
x1 = unit(1,"npc"),
y1 = unit(0,"npc"),
gp = gpar(lwd = 2.0)),
segmentsGrob( # diagonal line ll -> ur
x0 = unit(0,"npc"),
y0 = unit(0,"npc"),
x1 = unit(1,"npc"),
y1 = unit(1,"npc"),
gp = gpar(lwd = 2.0))),
t = 3, b = 3, l = 3, r = 3)
grid.draw(g)
## ----separators, fig.width=8---------------------------------------------
g <- tableGrob(head(iris), theme = ttheme_minimal())
separators <- replicate(ncol(g) - 2,
segmentsGrob(x1 = unit(0, "npc"), gp=gpar(lty=2)),
simplify=FALSE)
## add vertical lines on the left side of columns (after 2nd)
g <- gtable::gtable_add_grob(g, grobs = separators,
t = 2, b = nrow(g), l = seq_len(ncol(g)-2)+2)
grid.draw(g)
## ----highlight-----------------------------------------------------------
g <- tableGrob(iris[1:4, 1:3])
find_cell <- function(table, row, col, name="core-fg"){
l <- table$layout
which(l$t==row & l$l==col & l$name==name)
}
ind <- find_cell(g, 3, 2, "core-fg")
ind2 <- find_cell(g, 2, 3, "core-bg")
g$grobs[ind][[1]][["gp"]] <- gpar(fontsize=15, fontface="bold")
g$grobs[ind2][[1]][["gp"]] <- gpar(fill="darkolivegreen1", col = "darkolivegreen4", lwd=5)
grid.draw(g)
## ----ftable, fig.width=6-------------------------------------------------
grid.ftable <- function(d, padding = unit(4, "mm"), ...) {
nc <- ncol(d)
nr <- nrow(d)
## character table with added row and column names
extended_matrix <- cbind(c("", rownames(d)),
rbind(colnames(d),
as.matrix(d)))
## string width and height
w <- apply(extended_matrix, 2, strwidth, "inch")
h <- apply(extended_matrix, 2, strheight, "inch")
widths <- apply(w, 2, max)
heights <- apply(h, 1, max)
padding <- convertUnit(padding, unitTo = "in", valueOnly = TRUE)
x <- cumsum(widths + padding) - 0.5 * padding
y <- cumsum(heights + padding) - padding
rg <- rectGrob(x = unit(x - widths/2, "in"),
y = unit(1, "npc") - unit(rep(y, each = nc + 1), "in"),
width = unit(widths + padding, "in"),
height = unit(heights + padding, "in"))
tg <- textGrob(c(t(extended_matrix)), x = unit(x - widths/2, "in"),
y = unit(1, "npc") - unit(rep(y, each = nc + 1), "in"),
just = "center")
g <- gTree(children = gList(rg, tg), ...,
x = x, y = y, widths = widths, heights = heights)
grid.draw(g)
invisible(g)
}
grid.newpage()
grid.ftable(head(iris, 4), gp = gpar(fill = rep(c("grey90", "grey95"), each = 6)))
gridExtra/inst/doc/tableGrob.Rmd 0000644 0001762 0000144 00000024556 13152370532 016307 0 ustar ligges users ---
title: "Displaying tables as grid graphics"
author: "Baptiste Auguie"
date: '`r Sys.Date()`'
vignette: >
%\VignetteEngine{knitr::rmarkdown}
%\VignetteIndexEntry{tableGrob: displaying tables as grid graphics}
output:
knitr:::html_vignette:
toc: yes
---
```{r setup, echo=FALSE, results='hide'}
library(knitr)
opts_chunk$set(message=FALSE, fig.width=4, fig.height=2)
```
Tabular data is usually formatted outside the graphics device, e.g via LaTeX, or html tables. However, in some cases it may be convenient to display *small* tables alongside graphics. A couple of packages offer this possibility with base graphics (`plotrix` for instance); the `gridExtra` provides the pair of `tableGrob/grid.table` functions for this purpose.
*Note:* This vignette uses the development version of `gridExtra`, some features may not be yet available in the released version.
## Basic usage
```{r basic}
library(gridExtra)
library(grid)
d <- head(iris[,1:3])
grid.table(d)
```
## Spacing
The spacing of each row/column is automatic, and will adjust to bigger cell contents. Plotmath notation may be used, with the `parse=TRUE` argument. Note that this is applied to individual strings of text, and reverts to standard text if parsing fails (this is useful when mixing multiline text with plotmath in different cells).
```{r annotations, fig.height=3}
d[2,3] <- "this is very wwwwwide"
d[1,2] <- "this\nis\ntall"
colnames(d) <- c("alpha*integral(xdx,a,infinity)",
"this text\nis high", 'alpha/beta')
tt <- ttheme_default(colhead=list(fg_params = list(parse=TRUE)))
grid.table(d, theme=tt)
```
## Aesthetic formatting
The formatting is controlled by *themes*, which are nested lists of graphical parameters. See `ttheme_default` and `ttheme_minimal` for two built-in examples. Changing a few parameters at a time amounts to modifying the list with the new values.
```{r theme, fig.width=8}
tt1 <- ttheme_default()
tt2 <- ttheme_minimal()
tt3 <- ttheme_minimal(
core=list(bg_params = list(fill = blues9[1:4], col=NA),
fg_params=list(fontface=3)),
colhead=list(fg_params=list(col="navyblue", fontface=4L)),
rowhead=list(fg_params=list(col="orange", fontface=3L)))
grid.arrange(
tableGrob(iris[1:4, 1:2], theme=tt1),
tableGrob(iris[1:4, 1:2], theme=tt2),
tableGrob(iris[1:4, 1:2], theme=tt3),
nrow=1)
```
If the formatting values are fewer than the number of cells, they are recycled along columns,
```{r recycling}
t1 <- ttheme_default(core=list(
fg_params=list(fontface=c(rep("plain", 4), "bold.italic")),
bg_params = list(fill=c(rep(c("grey95", "grey90"),
length.out=4), "#6BAED6"),
alpha = rep(c(1,0.5), each=5))
))
grid.table(iris[1:5, 1:3], theme = t1)
```
## Text justification
The text labels can be justified; the default is "centre" for the core and header, and "right" for the row names. These settings can be adjusted by passing the relevant parameters of `textGrob` via the theme nested lists,
```{r justify, fig.width=8}
tt1 <- ttheme_default()
tt2 <- ttheme_default(core=list(fg_params=list(hjust=1, x=0.9)),
rowhead=list(fg_params=list(hjust=1, x=0.95)))
tt3 <- ttheme_default(core=list(fg_params=list(hjust=0, x=0.1)),
rowhead=list(fg_params=list(hjust=0, x=0)))
grid.arrange(
tableGrob(mtcars[1:4, 1:2], theme=tt1),
tableGrob(mtcars[1:4, 1:2], theme=tt2),
tableGrob(mtcars[1:4, 1:2], theme=tt3),
nrow=1)
```
## Further gtable processing and integration
Being based on `gtable`, the table can be further processed. In particular, we may edit the cell sizes to align with other content on the page.
```{r sizes, fig.width=8}
g <- g2 <- tableGrob(iris[1:4, 1:3], cols = NULL, rows=NULL)
g2$widths <- unit(rep(1/ncol(g2), ncol(g2)), "npc")
grid.arrange(rectGrob(), rectGrob(), nrow=1)
grid.arrange(g, g2, nrow=1, newpage = FALSE)
```
The alignment of several tables can be achieved with the `combine` function (adapted from `gtable:::join`),
```{r align, fig.width=6, fig.height=3}
d1 <- PlantGrowth[1:3,1, drop=FALSE]
d2 <- PlantGrowth[1:2,1:2]
g1 <- tableGrob(d1)
g2 <- tableGrob(d2)
haligned <- gtable_combine(g1,g2, along=1)
valigned <- gtable_combine(g1,g2, along=2)
grid.newpage()
grid.arrange(haligned, valigned, ncol=2)
```
### Borders and separators
Other grobs such as separating lines and rectangles (borders, boxes) may be added. In this case, keep in mind that row, column and cell numbering includes the column of row labels and the row of column labels *if they are present.* Let us illustrate this by adding some borders (using `rectGrob`) to a simple table without row numbers. We'll add two actually, to give a nice effect of a heavy line under the row of column headers.
```{r numberingDemo1}
library(gtable)
g <- tableGrob(iris[1:4, 1:3], rows = NULL)
g <- gtable_add_grob(g,
grobs = rectGrob(gp = gpar(fill = NA, lwd = 2)),
t = 2, b = nrow(g), l = 1, r = ncol(g))
g <- gtable_add_grob(g,
grobs = rectGrob(gp = gpar(fill = NA, lwd = 2)),
t = 1, l = 1, r = ncol(g))
grid.draw(g)
```
Note that when using `rectGrob` the top, bottom, left and right arguments (`t, b, l, r`) are the rows and columns which will be *inside* the rectangle. If we repeat the above code almost exactly, but don't suppress the column of row labels, we see that column 1 is now the column of row labels (and it doesn't look that good either, but that's not our point).
```{r numberingDemo2}
g <- tableGrob(iris[1:4, 1:3])
g <- gtable_add_grob(g,
grobs = rectGrob(gp = gpar(fill = NA, lwd = 2)),
t = 2, b = nrow(g), l = 1, r = ncol(g))
g <- gtable_add_grob(g,
grobs = rectGrob(gp = gpar(fill = NA, lwd = 2)),
t = 1, l = 1, r = ncol(g))
grid.draw(g)
```
When adding line segments to separate rows and columns using `segmentsGrob`, the row and column numbering scheme is the same (it includes any row or column labels). When working with line segments, you should keep in mind the default coordinate values for `segmentsGrob`. They are x0 = 0, y0 = 0, x1 = 1, y1 = 1, all in npc, relative to the cell(s) you are modifying, with the lower left corner being 0,0. For clarity, we show all the arguments in these examples. With this in mind, to add a line across the bottom of a single cell, use:
```{r segments1 }
g <- tableGrob(iris[1:4, 1:3])
g <- gtable_add_grob(g,
grobs = segmentsGrob( # line across the bottom
x0 = unit(0,"npc"),
y0 = unit(0,"npc"),
x1 = unit(1,"npc"),
y1 = unit(0,"npc"),
gp = gpar(lwd = 2.0)),
t = 3, b = 3, l = 3, r = 3)
grid.draw(g)
```
and to add a line to the left side:
```{r segments2 }
g <- tableGrob(iris[1:4, 1:3])
g <- gtable_add_grob(g,
grobs = segmentsGrob( # line across the bottom
x0 = unit(0,"npc"),
y0 = unit(0,"npc"),
x1 = unit(0,"npc"),
y1 = unit(1,"npc"),
gp = gpar(lwd = 2.0)),
t = 3, b = 3, l = 3, r = 3)
grid.draw(g)
```
Perhaps you'd like to cross out a cell. This can be done with two diagonal lines combined via a `grobTree`:
```{r segments3}
g <- tableGrob(iris[1:4, 1:3])
g <- gtable_add_grob(g,
grobs = grobTree(
segmentsGrob( # diagonal line ul -> lr
x0 = unit(0,"npc"),
y0 = unit(1,"npc"),
x1 = unit(1,"npc"),
y1 = unit(0,"npc"),
gp = gpar(lwd = 2.0)),
segmentsGrob( # diagonal line ll -> ur
x0 = unit(0,"npc"),
y0 = unit(0,"npc"),
x1 = unit(1,"npc"),
y1 = unit(1,"npc"),
gp = gpar(lwd = 2.0))),
t = 3, b = 3, l = 3, r = 3)
grid.draw(g)
```
If you have many cells to decorate you can use `replicate` to create create the segments. Just keep the `tableGrob` numbering scheme in mind.
```{r separators, fig.width=8}
g <- tableGrob(head(iris), theme = ttheme_minimal())
separators <- replicate(ncol(g) - 2,
segmentsGrob(x1 = unit(0, "npc"), gp=gpar(lty=2)),
simplify=FALSE)
## add vertical lines on the left side of columns (after 2nd)
g <- gtable::gtable_add_grob(g, grobs = separators,
t = 2, b = nrow(g), l = seq_len(ncol(g)-2)+2)
grid.draw(g)
```
### Accessing existing grobs in the table
We may also access and modify the original content of individual cells, e.g. to highlight a value.
```{r highlight}
g <- tableGrob(iris[1:4, 1:3])
find_cell <- function(table, row, col, name="core-fg"){
l <- table$layout
which(l$t==row & l$l==col & l$name==name)
}
ind <- find_cell(g, 3, 2, "core-fg")
ind2 <- find_cell(g, 2, 3, "core-bg")
g$grobs[ind][[1]][["gp"]] <- gpar(fontsize=15, fontface="bold")
g$grobs[ind2][[1]][["gp"]] <- gpar(fill="darkolivegreen1", col = "darkolivegreen4", lwd=5)
grid.draw(g)
```
## Faster tables: an alternative grid function
The `tableGrob` function can be very slow; unfortunately this is the price to pay for its versatility and easier implementation. We use individual `textGrob` and `rectGrob` elements for each cell, instead of relying on the vectorised implementation of these functions. The reason is practical: it is much easier to place, measure, and customise individual grobs, than modify the graphical parameters and positions of a single vectorised grob. An alternative function is presented below, using this vectorised approach, but lacking many of the customisations of `tableGrob`.
```{r ftable, fig.width=6}
grid.ftable <- function(d, padding = unit(4, "mm"), ...) {
nc <- ncol(d)
nr <- nrow(d)
## character table with added row and column names
extended_matrix <- cbind(c("", rownames(d)),
rbind(colnames(d),
as.matrix(d)))
## string width and height
w <- apply(extended_matrix, 2, strwidth, "inch")
h <- apply(extended_matrix, 2, strheight, "inch")
widths <- apply(w, 2, max)
heights <- apply(h, 1, max)
padding <- convertUnit(padding, unitTo = "in", valueOnly = TRUE)
x <- cumsum(widths + padding) - 0.5 * padding
y <- cumsum(heights + padding) - padding
rg <- rectGrob(x = unit(x - widths/2, "in"),
y = unit(1, "npc") - unit(rep(y, each = nc + 1), "in"),
width = unit(widths + padding, "in"),
height = unit(heights + padding, "in"))
tg <- textGrob(c(t(extended_matrix)), x = unit(x - widths/2, "in"),
y = unit(1, "npc") - unit(rep(y, each = nc + 1), "in"),
just = "center")
g <- gTree(children = gList(rg, tg), ...,
x = x, y = y, widths = widths, heights = heights)
grid.draw(g)
invisible(g)
}
grid.newpage()
grid.ftable(head(iris, 4), gp = gpar(fill = rep(c("grey90", "grey95"), each = 6)))
```
gridExtra/inst/doc/gtable.html 0000644 0001762 0000144 00000522066 13154617413 016071 0 ustar ligges users
The R package gtable is designed to help construct and manipulate layouts containing graphical elements. The standard grid package in R provides low-level functions to define viewports, and place graphical elements (grobs) at specific locations within the device window. gtable builds upon these functions and provides a higher-level interface, where one can e.g. merge two layouts, add columns, rows, insert graphical elements in a given cell, and change the display order, among other things.
The gtable package is used internally by ggplot2, and can therefore be used to modify the layout of such plots.
Constructing a gtable
A gtable object can be constructed in a variety of ways,
Empty table
gtable(unit(1:3, c("cm")), unit(5, "cm"))
This is an empty table with 3 rows and one column. gtable_col and gtable_row provide a simplified interface for 1 column or 1 row layouts, respectively.
matrix layout of grobs
a <-rectGrob(gp =gpar(fill ="red"))
b <-grobTree(rectGrob(), textGrob("new\ncell"))
c <-ggplotGrob(qplot(1:10,1:10))
d <-linesGrob()
mat <-matrix(list(a, b, c, d), nrow =2)
g <-gtable_matrix(name ="demo", grobs = mat,
widths =unit(c(2, 4), "cm"),
heights =unit(c(2, 5), c("in", "lines")))
g
Actual drawing of the gtable on a graphics device is performed with grid.draw(); note that plot() is only defined for debugging purposes, it adds a light grey background and thin grid lines to help visualise the scene in its drawing context.
plot(g)
grid.newpage()
grid.draw(g)
The gridExtra package provides a few conventient constructor functions, e.g.
where we note the dual nature of a gtable: it looks like a matrix, in the sense that it defines a rectangular table of nrow x ncol cells, but it’s also a list with an arbitrary length, defining where and how many grobs are to be placed in this tabular layout.
The most important components are,
grobs: This is a list of grobs of length(g). Grobs are placed in the tabular layout defined by the gtable, and multiple grobs can overlap and/or be stacked in the same cell(s).
length(g$grobs)
## [1] 4
layout: this is a data.frame indicating the position of each grob.
g$layout
## t l b r z clip name
## 1 1 1 1 1 1 on demo
## 2 2 1 2 1 2 on demo
## 3 1 2 1 2 3 on demo
## 4 2 2 2 2 4 on demo
The z-column is used to define the drawing order of the grobs, which becomes relevant when multiple grobs are stacked on top of each others. * widths and heights: this is the size description of the cells, given as grid units.
g$widths; g$heights
## [1] 2cm 4cm
## [1] 2in 5lines
Modifying a gtable
The gtable package defines several high-level functions to operate on a gtable object,
t.gtable to transpose the layout (future versions may support more general rotations)
[.gtable*, gtable_filter, gtable_trim to extract a portion of the gtable
cbind.gtable*, rbind.gtable* to combine 2 gtable objects (particularly useful for aligning multiple ggplots)
Manual operations at the low-level on the gtable can involve the grobs or the layout, but care should be taken to keep the two consistent (e.g. make sure that the length of both are in sync).
Examples to alter ggplot2 plots with gtable
The gtable tag on Stack Overlfow has several real-life examples using gtable to alter a ggplot2 before drawing.
The grid package provides low-level functions to create graphical objects (grobs), and position them on a page in specific viewports. The gtable package introduced a higher-level layout scheme, arguably more amenable to user-level interaction. With the arrangeGrob/grid.arrange() pair of functions, gridExtra builds upon gtable to arrange multiple grobs on a page.
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)
r <-rectGrob(gp=gpar(fill="grey90"))
t <-textGrob("text")
grid.arrange(t, p, p2, r, ncol=2)
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),
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, use arrangeGrob(),
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)
## non-interactive use, multipage pdf
## ggsave("multipage.pdf", ml)
## interactive use; calling `dev.new` multiple times
ml
gridExtra/inst/doc/gtable.Rmd 0000644 0001762 0000144 00000012474 13152370370 015640 0 ustar ligges users ---
title: "(Unofficial) overview of gtable"
author: "Baptiste Auguie"
date: '`r Sys.Date()`'
vignette: >
%\VignetteEngine{knitr::rmarkdown}
%\VignetteIndexEntry{(Unofficial) overview of gtable}
output:
knitr:::html_vignette:
toc: yes
---
```{r setup, echo=FALSE,message=FALSE}
require(knitr)
opts_chunk$set(fig.width=3,fig.height=3, tidy=FALSE, cache=FALSE, fig.path='gtable/')
require(gridExtra)
require(grid)
require(gtable)
require(ggplot2)
```
The R package `gtable` is designed to help construct and manipulate layouts containing graphical elements. The standard `grid` package in R provides low-level functions to define viewports, and place graphical elements (grobs) at specific locations within the device window. `gtable` builds upon these functions and provides a higher-level interface, where one can e.g. merge two layouts, add columns, rows, insert graphical elements in a given cell, and change the display order, among other things.
The `gtable` package is used internally by `ggplot2`, and can therefore be used to modify the layout of such plots.
### Constructing a gtable
A `gtable` object can be constructed in a variety of ways,
* Empty table
```{r, eval=FALSE}
gtable(unit(1:3, c("cm")), unit(5, "cm"))
```
This is an empty table with 3 rows and one column. `gtable_col` and `gtable_row` provide a simplified interface for 1 column or 1 row layouts, respectively.
* matrix layout of grobs
```{r matrix}
a <- rectGrob(gp = gpar(fill = "red"))
b <- grobTree(rectGrob(), textGrob("new\ncell"))
c <- ggplotGrob(qplot(1:10,1:10))
d <- linesGrob()
mat <- matrix(list(a, b, c, d), nrow = 2)
g <- gtable_matrix(name = "demo", grobs = mat,
widths = unit(c(2, 4), "cm"),
heights = unit(c(2, 5), c("in", "lines")))
g
```
Actual drawing of the gtable on a graphics device is performed with `grid.draw()`; note that `plot()` is only defined for debugging purposes, it adds a light grey background and thin grid lines to help visualise the scene in its drawing context.
```{r plot}
plot(g)
grid.newpage()
grid.draw(g)
```
The gridExtra package provides a few conventient constructor functions, e.g.
* based on `grid.arrange`
```{r gtable_arrange}
dummy_grob <- function(id) {
grobTree(rectGrob(gp=gpar(fill=id, alpha=0.5)), textGrob(id))
}
gs <- lapply(1:9, dummy_grob)
grid.arrange(ncol=4, grobs=gs,
top="top\nlabel", bottom="bottom\nlabel",
left="left\nlabel", right="right\nlabel")
grid.rect(gp=gpar(fill=NA))
```
* with a pre-defined layout
```{r gtable_from_layout}
gt <- arrangeGrob(grobs=gs, layout_matrix=rbind(c(1,1,1,2,3),
c(1,1,1,4,5),
c(6,7,8,9,9)))
grid.draw(gt)
grid.rect(gp=gpar(fill=NA))
```
### Components of a gtable
Let's have a closer look at the gtable we created earlier.
```{r}
print(g)
names(g)
```
Other useful characteristics of the gtable are,
```{r}
length(g); nrow(g); ncol(g)
```
where we note the dual nature of a gtable: it looks like a matrix, in the sense that it defines a rectangular table of nrow x ncol cells, but it's also a _list_ with an arbitrary length, defining where and how many grobs are to be placed in this tabular layout.
The most important components are,
* `grobs`: This is a list of grobs of `length(g)`. Grobs are placed in the tabular layout defined by the gtable, and multiple grobs can overlap and/or be stacked in the same cell(s).
```{r}
length(g$grobs)
```
* `layout`: this is a data.frame indicating the position of each grob.
```{r}
g$layout
```
The z-column is used to define the drawing order of the grobs, which becomes relevant when multiple grobs are stacked on top of each others.
* `widths` and `heights`: this is the size description of the cells, given as grid units.
```{r}
g$widths; g$heights
```
### Modifying a gtable
The gtable package defines several high-level functions to operate on a gtable object,
* `t.gtable` to transpose the layout (future versions may support more general rotations)
* `[.gtable*`, `gtable_filter`, `gtable_trim` to extract a portion of the gtable
* `cbind.gtable*`, `rbind.gtable*` to combine 2 gtable objects (particularly useful for aligning multiple ggplots)
* `gtable_add_cols`, `gtable_add_rows`,`gtable_add_col_space`, `gtable_add_row_space`, `gtable_add_padding`, `gtable_col_spacer`, `gtable_row_spacer`
Manual operations at the low-level on the gtable can involve the grobs or the layout, but care should be taken to keep the two consistent (e.g. make sure that the length of both are in sync).
#### Examples to alter ggplot2 plots with gtable
The `gtable` tag on Stack Overlfow has several real-life examples using gtable to alter a ggplot2 before drawing.
* aligning (multiple) [ggplot objects on a device](http://stackoverflow.com/a/17768224/471093), another [use-case scenario](http://stackoverflow.com/a/16798372/471093), aligning [base plot and ggplot](http://stackoverflow.com/a/14233531/471093)
* adding new grobs [aligned with the plot panel](http://stackoverflow.com/a/17371177/471093), also [this one](http://stackoverflow.com/a/17493256/471093)
* calculate [the device size based on the plot aspect ratio](http://stackoverflow.com/a/16442029/471093)
* add [new axes to a facet_grid layout](http://stackoverflow.com/a/17661337/471093), or a [second axis](http://stackoverflow.com/a/18511024/471093) gridExtra/inst/doc/arrangeGrob.rmd 0000644 0001762 0000144 00000006074 13152370123 016666 0 ustar ligges users ---
title: "Arranging multiple grobs on a page"
author: "Baptiste Auguie"
date: '`r Sys.Date()`'
vignette: >
%\VignetteEngine{knitr::rmarkdown}
%\VignetteIndexEntry{arrangeGrob: arranging multiple grobs on a page}
output:
knitr:::html_vignette:
toc: yes
---
```{r setup, echo=FALSE, results='hide'}
library(knitr)
opts_chunk$set(message=FALSE, fig.width=4, fig.height=3)
```
The `grid` package provides low-level functions to create graphical objects (`grobs`), and position them on a page in specific `viewports`. The `gtable` package introduced a higher-level layout scheme, arguably more amenable to user-level interaction. With the `arrangeGrob/grid.arrange()` pair of functions, `gridExtra` builds upon `gtable` to arrange multiple grobs on a page.
## Basic usage
In this example we mix a few grobs and plots,
```{r basic}
library(gridExtra)
library(grid)
library(ggplot2)
library(lattice)
p <- qplot(1,1)
p2 <- xyplot(1~1)
r <- rectGrob(gp=gpar(fill="grey90"))
t <- textGrob("text")
grid.arrange(t, p, p2, r, ncol=2)
```
## Title and/or annotations
```{r annotations}
gs <- lapply(1:9, function(ii)
grobTree(rectGrob(gp=gpar(fill=ii, alpha=0.5)), textGrob(ii)))
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
We can provide a matrix defining the layout,
```{r 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),
```{r holes}
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`),
```{r sizes, fig.height=2}
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, use `arrangeGrob()`,
```{r grob}
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()`.
```{r marrange}
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)
## non-interactive use, multipage pdf
## ggsave("multipage.pdf", ml)
## interactive use; calling `dev.new` multiple times
ml
```
gridExtra/inst/doc/ngonGrob.R 0000644 0001762 0000144 00000002232 13154617413 015627 0 ustar ligges users ## ----setup, echo=FALSE, results='hide'-----------------------------------
library(knitr)
opts_chunk$set(message=FALSE, fig.width=4, fig.height=3)
## ----basic---------------------------------------------------------------
library(gridExtra)
library(grid)
library(grid)
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-------------------------------------------------------------
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)
## ----ellipse-------------------------------------------------------------
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)
gridExtra/inst/doc/gtable.R 0000644 0001762 0000144 00000004002 13154617412 015306 0 ustar ligges users ## ----setup, echo=FALSE,message=FALSE-------------------------------------
require(knitr)
opts_chunk$set(fig.width=3,fig.height=3, tidy=FALSE, cache=FALSE, fig.path='gtable/')
require(gridExtra)
require(grid)
require(gtable)
require(ggplot2)
## ---- eval=FALSE---------------------------------------------------------
# gtable(unit(1:3, c("cm")), unit(5, "cm"))
## ----matrix--------------------------------------------------------------
a <- rectGrob(gp = gpar(fill = "red"))
b <- grobTree(rectGrob(), textGrob("new\ncell"))
c <- ggplotGrob(qplot(1:10,1:10))
d <- linesGrob()
mat <- matrix(list(a, b, c, d), nrow = 2)
g <- gtable_matrix(name = "demo", grobs = mat,
widths = unit(c(2, 4), "cm"),
heights = unit(c(2, 5), c("in", "lines")))
g
## ----plot----------------------------------------------------------------
plot(g)
grid.newpage()
grid.draw(g)
## ----gtable_arrange------------------------------------------------------
dummy_grob <- function(id) {
grobTree(rectGrob(gp=gpar(fill=id, alpha=0.5)), textGrob(id))
}
gs <- lapply(1:9, dummy_grob)
grid.arrange(ncol=4, grobs=gs,
top="top\nlabel", bottom="bottom\nlabel",
left="left\nlabel", right="right\nlabel")
grid.rect(gp=gpar(fill=NA))
## ----gtable_from_layout--------------------------------------------------
gt <- arrangeGrob(grobs=gs, layout_matrix=rbind(c(1,1,1,2,3),
c(1,1,1,4,5),
c(6,7,8,9,9)))
grid.draw(gt)
grid.rect(gp=gpar(fill=NA))
## ------------------------------------------------------------------------
print(g)
names(g)
## ------------------------------------------------------------------------
length(g); nrow(g); ncol(g)
## ------------------------------------------------------------------------
length(g$grobs)
## ------------------------------------------------------------------------
g$layout
## ------------------------------------------------------------------------
g$widths; g$heights
gridExtra/inst/doc/ngonGrob.Rmd 0000644 0001762 0000144 00000003046 13152370460 016150 0 ustar ligges users ---
title: "Regular polygons and ellipses in grid graphics"
author: "Baptiste Auguie"
date: '`r Sys.Date()`'
vignette: >
%\VignetteEngine{knitr::rmarkdown}
%\VignetteIndexEntry{ngonGrob: regular polygons and ellipses in grid graphics}
output:
knitr:::html_vignette:
toc: yes
---
```{r setup, echo=FALSE, results='hide'}
library(knitr)
opts_chunk$set(message=FALSE, fig.width=4, fig.height=3)
```
The `gridExtra` package provides a basic implementation of regular polygons, `ngonGrob()/grid.ngon`, and a convenience function to draw ellipses, `ellipseGrob()/grid.ellipse()`. We illustrate below the basic usage of these vectorised functions.
## Basic usage
```{r basic}
library(gridExtra)
library(grid)
library(grid)
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 stretched polygons
```{r rotated}
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
```{r ellipse}
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)
```
gridExtra/inst/doc/tableGrob.html 0000644 0001762 0000144 00003224321 13154617417 016534 0 ustar ligges users
Displaying tables as grid graphics
Tabular data is usually formatted outside the graphics device, e.g via LaTeX, or html tables. However, in some cases it may be convenient to display small tables alongside graphics. A couple of packages offer this possibility with base graphics (plotrix for instance); the gridExtra provides the pair of tableGrob/grid.table functions for this purpose.
Note: This vignette uses the development version of gridExtra, some features may not be yet available in the released version.
Basic usage
library(gridExtra)
library(grid)
d <-head(iris[,1:3])
grid.table(d)
Spacing
The spacing of each row/column is automatic, and will adjust to bigger cell contents. Plotmath notation may be used, with the parse=TRUE argument. Note that this is applied to individual strings of text, and reverts to standard text if parsing fails (this is useful when mixing multiline text with plotmath in different cells).
d[2,3] <- "this is very wwwwwide"
d[1,2] <- "this\nis\ntall"colnames(d) <-c("alpha*integral(xdx,a,infinity)",
"this text\nis high", 'alpha/beta')
tt <-ttheme_default(colhead=list(fg_params =list(parse=TRUE)))
grid.table(d, theme=tt)
Aesthetic formatting
The formatting is controlled by themes, which are nested lists of graphical parameters. See ttheme_default and ttheme_minimal for two built-in examples. Changing a few parameters at a time amounts to modifying the list with the new values.
The text labels can be justified; the default is “centre†for the core and header, and “right†for the row names. These settings can be adjusted by passing the relevant parameters of textGrob via the theme nested lists,
Other grobs such as separating lines and rectangles (borders, boxes) may be added. In this case, keep in mind that row, column and cell numbering includes the column of row labels and the row of column labels if they are present. Let us illustrate this by adding some borders (using rectGrob) to a simple table without row numbers. We’ll add two actually, to give a nice effect of a heavy line under the row of column headers.
library(gtable)
g <-tableGrob(iris[1:4, 1:3], rows =NULL)
g <-gtable_add_grob(g,
grobs =rectGrob(gp =gpar(fill =NA, lwd =2)),
t =2, b =nrow(g), l =1, r =ncol(g))
g <-gtable_add_grob(g,
grobs =rectGrob(gp =gpar(fill =NA, lwd =2)),
t =1, l =1, r =ncol(g))
grid.draw(g)
Note that when using rectGrob the top, bottom, left and right arguments (t, b, l, r) are the rows and columns which will be inside the rectangle. If we repeat the above code almost exactly, but don’t suppress the column of row labels, we see that column 1 is now the column of row labels (and it doesn’t look that good either, but that’s not our point).
g <-tableGrob(iris[1:4, 1:3])
g <-gtable_add_grob(g,
grobs =rectGrob(gp =gpar(fill =NA, lwd =2)),
t =2, b =nrow(g), l =1, r =ncol(g))
g <-gtable_add_grob(g,
grobs =rectGrob(gp =gpar(fill =NA, lwd =2)),
t =1, l =1, r =ncol(g))
grid.draw(g)
When adding line segments to separate rows and columns using segmentsGrob, the row and column numbering scheme is the same (it includes any row or column labels). When working with line segments, you should keep in mind the default coordinate values for segmentsGrob. They are x0 = 0, y0 = 0, x1 = 1, y1 = 1, all in npc, relative to the cell(s) you are modifying, with the lower left corner being 0,0. For clarity, we show all the arguments in these examples. With this in mind, to add a line across the bottom of a single cell, use:
g <-tableGrob(iris[1:4, 1:3])
g <-gtable_add_grob(g,
grobs =segmentsGrob( # line across the bottomx0 =unit(0,"npc"),
y0 =unit(0,"npc"),
x1 =unit(1,"npc"),
y1 =unit(0,"npc"),
gp =gpar(lwd =2.0)),
t =3, b =3, l =3, r =3)
grid.draw(g)
and to add a line to the left side:
g <-tableGrob(iris[1:4, 1:3])
g <-gtable_add_grob(g,
grobs =segmentsGrob( # line across the bottomx0 =unit(0,"npc"),
y0 =unit(0,"npc"),
x1 =unit(0,"npc"),
y1 =unit(1,"npc"),
gp =gpar(lwd =2.0)),
t =3, b =3, l =3, r =3)
grid.draw(g)
Perhaps you’d like to cross out a cell. This can be done with two diagonal lines combined via a grobTree:
g <-tableGrob(iris[1:4, 1:3])
g <-gtable_add_grob(g,
grobs =grobTree(
segmentsGrob( # diagonal line ul -> lrx0 =unit(0,"npc"),
y0 =unit(1,"npc"),
x1 =unit(1,"npc"),
y1 =unit(0,"npc"),
gp =gpar(lwd =2.0)),
segmentsGrob( # diagonal line ll -> urx0 =unit(0,"npc"),
y0 =unit(0,"npc"),
x1 =unit(1,"npc"),
y1 =unit(1,"npc"),
gp =gpar(lwd =2.0))),
t =3, b =3, l =3, r =3)
grid.draw(g)
If you have many cells to decorate you can use replicate to create create the segments. Just keep the tableGrob numbering scheme in mind.
g <-tableGrob(head(iris), theme =ttheme_minimal())
separators <-replicate(ncol(g) -2,
segmentsGrob(x1 =unit(0, "npc"), gp=gpar(lty=2)),
simplify=FALSE)
## add vertical lines on the left side of columns (after 2nd)
g <-gtable::gtable_add_grob(g, grobs = separators,
t =2, b =nrow(g), l =seq_len(ncol(g)-2)+2)
grid.draw(g)
Accessing existing grobs in the table
We may also access and modify the original content of individual cells, e.g. to highlight a value.
g <-tableGrob(iris[1:4, 1:3])
find_cell <-function(table, row, col, name="core-fg"){
l <-table$layout
which(l$t==row &l$l==col &l$name==name)
}
ind <-find_cell(g, 3, 2, "core-fg")
ind2 <-find_cell(g, 2, 3, "core-bg")
g$grobs[ind][[1]][["gp"]] <-gpar(fontsize=15, fontface="bold")
g$grobs[ind2][[1]][["gp"]] <-gpar(fill="darkolivegreen1", col ="darkolivegreen4", lwd=5)
grid.draw(g)
Faster tables: an alternative grid function
The tableGrob function can be very slow; unfortunately this is the price to pay for its versatility and easier implementation. We use individual textGrob and rectGrob elements for each cell, instead of relying on the vectorised implementation of these functions. The reason is practical: it is much easier to place, measure, and customise individual grobs, than modify the graphical parameters and positions of a single vectorised grob. An alternative function is presented below, using this vectorised approach, but lacking many of the customisations of tableGrob.
grid.ftable <-function(d, padding =unit(4, "mm"), ...) {
nc <-ncol(d)
nr <-nrow(d)
## character table with added row and column names
extended_matrix <-cbind(c("", rownames(d)),
rbind(colnames(d),
as.matrix(d)))
## string width and height
w <-apply(extended_matrix, 2, strwidth, "inch")
h <-apply(extended_matrix, 2, strheight, "inch")
widths <-apply(w, 2, max)
heights <-apply(h, 1, max)
padding <-convertUnit(padding, unitTo ="in", valueOnly =TRUE)
x <-cumsum(widths +padding) -0.5*padding
y <-cumsum(heights +padding) -padding
rg <-rectGrob(x =unit(x -widths/2, "in"),
y =unit(1, "npc") -unit(rep(y, each = nc +1), "in"),
width =unit(widths +padding, "in"),
height =unit(heights +padding, "in"))
tg <-textGrob(c(t(extended_matrix)), x =unit(x -widths/2, "in"),
y =unit(1, "npc") -unit(rep(y, each = nc +1), "in"),
just ="center")
g <-gTree(children =gList(rg, tg), ...,
x = x, y = y, widths = widths, heights = heights)
grid.draw(g)
invisible(g)
}
grid.newpage()
grid.ftable(head(iris, 4), gp =gpar(fill =rep(c("grey90", "grey95"), each =6)))
gridExtra/inst/doc/ngonGrob.html 0000644 0001762 0000144 00000375254 13154617413 016413 0 ustar ligges users
Regular polygons and ellipses in grid graphics
The gridExtra package provides a basic implementation of regular polygons, ngonGrob()/grid.ngon, and a convenience function to draw ellipses, ellipseGrob()/grid.ellipse(). We illustrate below the basic usage of these vectorised functions.
Basic usage
library(gridExtra)
library(grid)
library(grid)
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)