2

I have four goals:

  1. Connect to a Postgresql database and pull some data
  2. Gloss up a table with some colour and formatting
  3. Include an image (company logo) above it
  4. Export as PDF

1 and 2 are easy enough and 4 seems possible even if not convenient, but I don't think R was designed to add and position images. I've attached some sample code of how I envision creating the table, and then a mockup of what I think the final version might look like. Can anyone advise on the best way to accomplish this?

Sample data:

data(mtcars)
df <- head(mtcars)

HTML approach: flexible and portable to other apps

library(tableHTML)
html_table <- df %>%
  tableHTML(rownames = FALSE, border = 0) %>%
  add_css_row(css = list(c('font-family', 'text-align'), c('sans-serif', 'center'))) %>%
  add_css_header(css = list(c('background-color', 'color'), c('#173ACC', 'white')), headers = 1:ncol(df))

Grob approach: Creating a ggplot-like image. I've seen recommendations to use grid.arrange to place an image on top and export as a PDF

library(ggpubr)
tbody.style = tbody_style(color = "black",
                          fill = "white", hjust=1, x=0.9)
grob_table <- ggtexttable(df, rows = NULL,
                           theme = ttheme(
                             colnames.style = colnames_style(color = "white", fill = "#173ACC"),
                             tbody.style = tbody.style
                           )
)
grid.arrange(table_image)

Expected Output

Nicholas Hassan
  • 949
  • 2
  • 10
  • 27
  • Have you tried knitr with tinytex in R markdown? Making pdfs and other documents from data in structured formats is its purpose. https://stackoverflow.com/questions/25166624/insert-picture-table-in-r-markdown – dcsuka Jul 29 '22 at 23:17

1 Answers1

0

You are almost there. You just need to import your image (could be png, jpeg or svg) then pass it to grid::rasterGrob. Use the options in rasterGrob to adjust size etc. Then pass your grob table to gridExtra::grid.arrange

logo_imported <- png::readPNG(system.file("img", "Rlogo.png", package="png"), TRUE)
lg <- grid::rasterGrob(logo_imported)

gridExtra::grid.arrange(lg, grob_table)

You can then either render this to pdf by adding it to an rmarkdown report (probably best), or you can save directly to pdf via

gridExtra::grid.arrange(lg, grob_table)

pdf(file = "My Plot.pdf",   
    width = 4, # The width of the plot in inches
    height = 4)
mrjoh3
  • 437
  • 2
  • 11