Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

r - plot xtable or save it as image

I want to use xtable layouts in my powerpoint presentations and I need a way to directly convert a data.frame into a picture or plot of an xtable such as the ones displayed here.

The ideal solution would give me a ggplot object as I have the most flexibility from there, but I can work with another output as long as I can see a xtable in a pic (raster or vector) or plot window.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Using ggplot2 and grid.extra we can achieve decently looking tables:

library(ggplot2)
library(gridExtra)
ggplot() + annotation_custom(tableGrob(head(iris))) + theme_void()

tableGrob has a theme parameter that allows enough flexibility to reproduce something close to xtable. see this vignette.

Here's a convenient function to do a bit more, you'll need packages grid and gtable :

table_plot <- function(x,
                       theme_fun= gridExtra::ttheme_minimal,
                       base_size = 12,
                       base_colour = "black",
                       base_family = "",
                       parse = FALSE,
                       padding = unit(c(4, 4), "mm"),
                       col = base_colour,
                       lwd=1,
                       lty=1
                       ){
  g <- gridExtra::tableGrob(x,
    theme = theme_fun(base_size, base_colour, base_family, parse, padding))
  separators <- replicate(ncol(g) - 2,
                          grid::segmentsGrob(x1 = unit(0, "npc"), gp=gpar(col=col,lwd=lwd,lty=lty)),
                          simplify=FALSE)
  g <- gtable::gtable_add_grob(g, grobs = separators,
                               t = 2, b = nrow(g), l = seq_len(ncol(g)-2)+2)
  ggplot2::ggplot() + ggplot2::annotation_custom(g) + ggplot2::theme_void()
}

simple example:

table_plot(head(iris))

complicated example :

iris2 <- setNames(head(iris)[1:3],c("alpha*integral(xdx,a,infinity)", "this text
is high", 'alpha/beta'))
table_plot(iris2,
           base_size=10,
           base_colour="darkred",
           base_family = "serif",
           parse=TRUE,
           theme=ttheme_default,
           lwd=3,
           lty=2,
           col="darkblue")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...