32

I would like to export a data frame as a (png) image. I've tried with this code, but the table get clipped vertically.

library(ggplot2)
library(gridExtra)

df <- data.frame(a=1:30, b=1:30)

png("test.png")
p<-tableGrob(df)
grid.arrange(p)
dev.off()

Is there a way to avoid this behaviour without having to set manually the size of the image?

Andrea Valsecchi
  • 321
  • 1
  • 3
  • 4
  • 4
    You could also try the `xtables` package to reder it as a \LaTeX table and exporting as a PDF. It is much more customizable. – Oscar de León Apr 29 '14 at 12:57

4 Answers4

23

You can change this behavior by specifying a height and width.

png("test.png", height=1000, width=200)
p<-tableGrob(df)
grid.arrange(p)
dev.off()

Anyway, it is usually not very helpful to save tables as pictures.

shadow
  • 21,823
  • 4
  • 63
  • 77
18

You can do like this:

library(gridExtra)
png("test.png", height = 50*nrow(df), width = 200*ncol(df))
grid.table(df)
dev.off()
Ning
  • 514
  • 5
  • 5
0

This works just fine:

library(gridExtra)

df = data.frame("variables" = c("d_agr","d_def","d_frig","d_hidro","d_roads","d_silos"),
"coeficient" = c(0.18,0.19,-0.01,-0.25,-0.17,0.09))

png("output.png", width=480,height=480,bg = "white")
grid.table(df)
dev.off()
0

To get the size of the table you have to generate a tableGrob first, than you can get the height and width parameters. The parameters are "grobwidth", they have to be converted into inch.

Here is my solution (base on gridExtra vignettes), it works fine for me.

library(grid)
library(gridExtra)
gridFtable <- function(d, pd = 4, fontsize = 10, fontfamily = "PT Mono") {
    
    ## set plot theme
    t1 <- ttheme_default(padding = unit(c(pd, pd), "mm"), base_size = fontsize, base_family = fontfamily)
    
    ## character table with added row and column names
    extended_matrix <- cbind(c("", rownames(d)), rbind(colnames(d), as.matrix(d)))
    
    ## get grob values
    g <- tableGrob(extended_matrix, theme = t1)
    
    ## convert widths from grobwidth to inch
    widthsIn <- lapply(g$widths, function(x) {convertUnit(x, unitTo = "inch", valueOnly = TRUE)})
    heigthsIn <- lapply(g$heights, function(x) {convertUnit(x, unitTo = "inch", valueOnly = TRUE)})
    
    ## calculate width and height of the table
    w <- sum(unlist(widthsIn)) - 1*convertUnit(unit(pd, "mm"), unitTo = "inch", valueOnly = TRUE)
    h <- sum(unlist(heigthsIn)) - 1*convertUnit(unit(pd, "mm"), unitTo = "inch", valueOnly = TRUE)
    
    return(list(grobData = g, data = d, width = w, heigth = h, theme = t1))
}

saveTable <- gridFtable(data.frame(a=1:30, b=1:30))
png(file = "./test.png", width = saveTable$width, height = saveTable$heigth, units = "in", res = 100)
grid.newpage()
grid.table(saveTable$data, rows = NULL, theme = saveTable$theme)
dev.off()
getwd()