Skip to content

Instantly share code, notes, and snippets.

@baptiste
Created July 4, 2023 20:40
Show Gist options
  • Save baptiste/23efe856d4c4795db3be6eafc543d0ff to your computer and use it in GitHub Desktop.
Save baptiste/23efe856d4c4795db3be6eafc543d0ff to your computer and use it in GitHub Desktop.
---
title: "Untitled"
format:
pdf:
latex-tinytex: false
keep-md: true
keep-tex: true
fontsize: "11"
---
```{r}
library(knitr)
library(glue)
library(gt)
if(!require(webshot2)) warning("you'll need this")
knit_print.gt_tbl = function(x, ...) {
if(!knitr::is_latex_output()){
return(gt:::knit_print.gt_tbl(x, ...))
}
f <- glue("{opts_current$get('label')}-gt_tbl.png")
x |> gtsave(filename=f,
zoom = 1,expand=5)
size <- dim(png::readPNG(f)) # overkill, probably better ways with magic
knitr::asis_output(glue("\\centering\\includegraphics[width=<size[1]>\\pixel,height=<size[2]>\\pixel]{<f>}", .open="<",.close=">"))
}
registerS3method(
"knit_print", "gt_tbl", knit_print.gt_tbl,
envir = asNamespace("knitr")
)
```
\newlength{\pixel} \setlength{\pixel}{\dimexpr 1in/72}
```{r}
tbl <- countrypops |>
dplyr::filter(country_code_3 %in% c("FRA", "GBR", "ITA")) |>
dplyr::select(-contains("code")) |>
dplyr::filter(year %% 5 == 0) |>
tidyr::pivot_wider(
names_from = "country_name",
values_from = "population"
) |>
gt() |> tab_options(
table.font.size = px(11L)
) |>
fmt_integer(columns = c(everything(), -year)) |>
cols_width(
year ~ px(80),
everything() ~ px(160)
) |>
opt_table_font(stack = "old-style") |>
opt_all_caps() |>
opt_vertical_padding(scale = 0.75) |>
opt_horizontal_padding(scale = 3) |>
data_color(
columns = year,
target_columns = everything(),
palette = "inferno"
) |>
tab_options(
table_body.hlines.style = "none",
column_labels.border.top.color = "black",
column_labels.border.bottom.color = "black",
table_body.border.bottom.color = "black"
)
tbl
```
```{r, results='asis'}
tbl |> as_latex()
```
@baptiste
Copy link
Author

baptiste commented Jul 4, 2023

Screenshot 2023-07-05 at 08 40 09

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment