【问题标题】:R save table as imageR将表格另存为图像
【发布时间】:2014-04-29 12:46:48
【问题描述】:

我想将数据框导出为 (png) 图像。我试过这段代码,但表格被垂直剪裁了。

library(ggplot2)
library(gridExtra)

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

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

有没有办法避免这种行为而无需手动设置图像的大小?

【问题讨论】:

  • 您也可以尝试使用xtables 包将其重新生成为 \LaTeX 表并导出为 PDF。它的可定制性更高。

标签: r plot


【解决方案1】:

您可以通过指定高度和宽度来更改此行为。

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

无论如何,将表格另存为图片通常不是很有帮助。

【讨论】:

  • 有没有办法根据表格大小自动设置图片大小?
  • 你可以使用height=350*nrow(df)width=80*ncol(df)之类的东西
【解决方案2】:

你可以这样做:

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

【讨论】:

    【解决方案3】:

    这很好用:

    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()
    

    【讨论】:

    • 这对之前的答案没有任何价值,这个答案的目的是什么?
    【解决方案4】:

    要获得表格的大小,您必须先生成一个 tableGrob,然后才能获得 heightwidth 参数。参数是“grobwidth”,必须转换成英寸。

    这是我的解决方案(基于 gridExtra vignettes),对我来说效果很好。

    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()
    

    【讨论】:

      猜你喜欢
      • 2012-03-24
      • 2016-07-18
      • 2018-01-06
      • 2014-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多