Save a flextable as an image

[This article was first published on R on ArData, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

flextable 0.5.4 is now on CRAN. It contains a new output option that some users were asking: image output. You can now save a flextable as a png or pdf file with function save_as_image.

The solution was existing since a long time but was buried in a stackoverflow question instead of being provided in flextable as an option.

This functionality is letting other options to be available, you can now use method plot and also as_raster and do whatever you’d like with the raster (combine with a ggplot object for example).

Demo

First, let’s create a simple flextable.

library(flextable)
ft <- flextable( head( mtcars ) )
ft <- autofit(ft)
ft

You can save it as a png:

save_as_image(ft, path = "name.png")

You can plot it:

plot(ft)

Or combine the table with a ggplot object:

library(ggplot2)
library(grid)
library(cowplot)

ft_raster <- as_raster(ft)

anyplot <- qplot(speed, dist, data = cars, geom = "point")

gflextable <- ggplot() + 
  theme_void() + 
  annotation_custom(rasterGrob(ft_raster), xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf)

plot_grid(anyplot, gflextable, nrow = 2, ncol = 1, rel_heights = c(4, 1) )

About width and height

When a flextable is printed, it may be useful to know the exact width and height of the table to be sure to set up the correct aspect ratio. The function flextable_dim() will provide these informations without the need to produce the image.

dims <- flextable_dim(ft)
dims
#> $widths
#> [1] 7.948045
#> 
#> $heights
#> [1] 2.035298
#> 
#> $aspect_ratio
#> [1] 0.2560753

You can reuse them as values for knitr chunk options fig.asp, fig.width and fig.height.

To leave a comment for the author, please follow the link and comment on their blog: R on ArData.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)