Reputation: 321
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?
Upvotes: 32
Views: 62057
Reputation: 33
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()
Upvotes: 0
Reputation: 1
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()
Upvotes: 0
Reputation: 534
You can do like this:
library(gridExtra)
png("test.png", height = 50*nrow(df), width = 200*ncol(df))
grid.table(df)
dev.off()
Upvotes: 19
Reputation: 22293
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.
Upvotes: 23