jthomasmock / gtExtras

A Collection of Helper Functions for the gt Package.
https://jthomasmock.github.io/gtExtras/
Other
193 stars 26 forks source link

Curious behaviour of `gt_plt_dist()` in RMarkdown when using `print()` #56

Closed AshesITR closed 2 years ago

AshesITR commented 2 years ago

First of all, thanks for this very great package!

I noticed some very curious behavior when knitting an Rmd using a results = asis chunk for generating a large number of tables in a for loop. Here's a minimal example Rmd:

---
title: "Demo"
output: html_document
---

```{r}
dummy_data <- tibble::tibble(
  a = 1:2,
  b = list(1:2, 3:4)
)

Auto-printing

gt::gt(dummy_data) |>
  gtExtras::gt_plt_dist(column = b, type = "histogram")

Maunal printing (using results = asis)

gt::gt(dummy_data) |>
  gtExtras::gt_plt_dist(column = b, type = "histogram") |>
  print()
gt::gt(dummy_data) |>
  gtExtras::gt_plt_dist(column = b, type = "histogram") |>
  knitr::knit_print()


It produces a misaligned second row when using `base::print()` to display the table from an asis-chunk.
I'm used to `print()` just working in Rmd and it does work correctly on a plain `gt::gt()`, i.e. if I'm not using `gtExtras::gt_plt_dist()`.

![rendered document](https://user-images.githubusercontent.com/2363178/174592637-16c43151-7f5b-4db8-9374-72fc9f383eb4.png)

Now while I already found the solution (just use `knitr::knit_print()`), I still wonder why that is the case.
jthomasmock commented 2 years ago

Thanks for the reprex here - please note that I have provided a solution in your other issue #57.

I will keep this issue open as I explore the optimal approach and whether there needs to be an alternate print method in gtExtras or if I need to open an issue on gt itself.

jthomasmock commented 2 years ago

I believe this is functionally solved by using knit_print() |> cat() in a results='asis' chunk.

Thus the two approaches are working:

---
title: "R Notebook"
output: html_document
---
```{r}
library(gt)
library(ggplot2)
dummy_data <- tibble::tibble(
  a = 1:2,
  b = list(1:2, 3:4)
)
f <- function() {
  tbl <- gt::gt(dummy_data) |>
    gtExtras::gt_plt_dist(column = b, type = "histogram") |> 
    knitr::knit_print() |> 
    cat()
}

for (i in 1) {
  f()
  cat("boop.\n")
}
f <- function() {
  tbl <- gt::gt(dummy_data) |>
    gtExtras::gt_plt_dist(column = b, type = "histogram") |> 
    gt::as_raw_html() |> 
    gsub(x = _, pattern = "\\s+", " ") |> 
    gt::html() |> 
    print()

}

for (i in 1) {
  f()
  cat("boop.\n")
}

![Screen Shot 2022-06-20 at 6 36 33 PM](https://user-images.githubusercontent.com/29187501/174689086-a03e26d5-7662-4dde-8419-fb8ea0c9f6ab.png)