rstudio / gt

Easily generate information-rich, publication-quality tables from R
https://gt.rstudio.com
Other
2.03k stars 209 forks source link

Table.width = pct(100) ignored in pdf #329

Closed fabiangehring closed 3 months ago

fabiangehring commented 5 years ago

hi,

Setting the tab_options(table.width = pct(100)) does not seem to have the desired effect when creating pdfs.

---
title: "Test"
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(gt)
library(tidyverse)
library(glue)

# Define the start and end dates for the data range
start_date <- "2010-06-07"
end_date <- "2010-06-14"

# Create a gt table based on preprocessed
# `sp500` table data
sp500 %>%
  dplyr::filter(date >= start_date & date <= end_date) %>%
  dplyr::select(-adj_close) %>%
  gt() %>%
  tab_header(
    title = "S&P 500",
    subtitle = glue::glue("{start_date} to {end_date}")
  ) %>%
  fmt_date(
    columns = vars(date),
    date_style = 3
  ) %>%
  fmt_currency(
    columns = vars(open, high, low, close),
    currency = "USD"
  ) %>%
  fmt_number(
    columns = vars(volume),
    suffixing = TRUE
  ) %>% tab_options(
    table.width = pct(100)
  )
rich-iannone commented 5 years ago

Thanks for filing this issue. We do have quite a few things not yet implemented in anything other than HTML. We will get to those! We just need to make sure everything is solid for HTML, then we’ll make sure things like this work in LaTeX and RTF.

krhemanth commented 4 years ago

Hello @rich-iannone I face the same issue in html with tab_options I could do row_padding, but when it comes to table.width = pct(100), I get a horizontal scroll bar, I want to display my entire table having 8 rows and 7 columns .

data_frm_tbl %>% gt() %>% tab_header( title = "Total tested and total tested diabetic", subtitle = glue::glue("Patient Count") ) %>% cols_width( starts_with("n") ~ px(175), starts_with("H") ~ px(175), starts_with("d") ~ px(145), starts_with("t") ~ px(120), TRUE ~ px(80) ) %>% tab_options( table.width = pct(100), row.padding = px(3) )


Please help me if I am making any mistake. Thank you.
krhemanth commented 4 years ago

And @rich-iannone when I render table using gt why is my table having a darker shade for every alternate row , how can I remove the dark shade, so that it looks like perfect clean table with uniform shade in every row. Thanks. Please give me suggestions asap. Thanks for your work with gt its great.

rich-iannone commented 4 years ago

@krhemanth To turn the row striping off, we can use an option in tab_options():

exibble %>%
  gt() %>%
  tab_options(row.striping.include_table_body = FALSE)

In a later update, having unstriped rows will be the default (requiring the use of a function or tab_options() to enable). But, for now, this is the only way to disable them.

krhemanth commented 4 years ago

@rich-iannone Thanks so much for your response, But I dint find any changes from using [tab_options(row.striping.include_table_body = FALSE)] I still get scroll bar , so I increased my Rmarkdown default width, so now I get my complete table,

And Now how can I remove the dark shade appearing in every alternate row, by default. This does not make the output look like a normal table. Thanks once again.

rich-iannone commented 4 years ago

The above code example (with tab_options()) should make the row shading disappear. Do you have the latest version of gt on master? Could you please install the latest using remotes::install_github("rstudio/gt") and try once more?

krhemanth commented 4 years ago

@rich-iannone when I try to install gt using the above command I get this error

remotes::install_github("rstudio/gt") Error: Failed to install 'gt' from GitHub: Timeout was reached: [api.github.com] Connection timed out after 10000 milliseconds

I use R 3.6.1 and I am not sure how to check my gt version, every time I run the code I load the package from.

pkglist <- c('dplyr', 'tsibble' ,'lubridate', 'stringr', 'mice', 'tidyr', 'data.table', 'summarytools', 'gt', 'kableExtra', 'knitr', 'xtable', 'ggplot2', 'stats', 'ggpubr', 'gganimate', 'ggrepel', 'zipcode' ,'noncensus', 'htmltools')

check.and.install.Package<-function(package_name){ if (!package_name %in% installed.packages()) { install.packages(package_name, repos='http://cran.us.r-project.org') } }

krhemanth commented 4 years ago

and I am using proxy server in my office will this be an problem for " remotes::install_github("rstudio/gt") " not working.

krhemanth commented 4 years ago

@rich-iannone Thanks so much,

tab_options(row.striping.include_table_body = FALSE) is working, my dark shade disappeared.. Thanks a ton... 🥇

krhemanth commented 4 years ago

@rich-iannone , Thanks for continuous support for my every question, I have come up with a new question, How can I create a border to the table generated using gt, example a vertical line in the left side and right side of the table so that it looks like a border for the entire table. Thank you.

krhemanth commented 4 years ago

Hello @rich-iannone ,

any leads for creating borders. in the all the four corners of the table,

BrennanHickson commented 10 months ago

Hello @rich-iannone I face the same issue in html with tab_options I could do row_padding, but when it comes to table.width = pct(100), I get a horizontal scroll bar, I want to display my entire table having 8 rows and 7 columns .

data_frm_tbl %>% gt() %>% tab_header( title = "Total tested and total tested diabetic", subtitle = glue::glue("Patient Count") ) %>% cols_width( starts_with("n") ~ px(175), starts_with("H") ~ px(175), starts_with("d") ~ px(145), starts_with("t") ~ px(120), TRUE ~ px(80) ) %>% tab_options( table.width = pct(100), row.padding = px(3) )

Please help me if I am making any mistake. Thank you.

@rich-iannone Are there any options available for setting responsive column/table widths for non-HTML files? My attempts to adjust the widths for a "gt_tbl" object that's then saved as a .png file have been unsuccessful so far... The resulting image shows only one column (i.e., the first column, "Characteristic") out of 9 total columns, and the overall table width appears to equal that of the original file with the default column/table width settings.

I haven't found any promising solutions to this problem, so I just wondered if you had any ideas!

olivroy commented 3 months ago

@kbrevoort Has this been fixed in gt 0.11?

kbrevoort commented 3 months ago

@olivroy Yes, setting table.width to pct(100) should be working for PDF output.

lokesh-krishna commented 2 months ago

On gt 0.11.0 and tab_options(table.width = pct(100)) still results in an overflowing table in PDF.

image

This is the code for my table. Am I missing anything?

tribble(
  ~"HBV vaccination status", ~"rn", ~"rp", ~"nn", ~"np", ~"int", ~"ip", ~"cn", ~"cp",
  "Never vaccinated", 0, "0%", 0, "0%", 1, "5.8%", 0, "0%",
  "Discontinued", 5, "5.6%", 0, "0%", 2, "11.7%", 3, "2%",
  "All doses completed", 83, "94.4%", 101, "100%", 14, "82.5%", 145, "98%"
) |>
  gt() |>
  grand_summary_rows(
    columns = c("nn", "cn", "rn", "int"),
    fns = list(id = "total", label = "Totals", fn = "sum")
  ) |>
  tab_spanner(
    label = "Nursing Staff",
    columns = c("nn", "np")
  ) |>
  tab_spanner(
    label = "Class IV Employees",
    columns = c("cn", "cp")
  ) |>
  tab_spanner(
    label = "Resident Doctors",
    columns = c("rn", "rp")
  ) |>
  tab_spanner(
    label = "Interns",
    columns = c("int", "ip")
  ) |>
  cols_label(
    nn = "n",
    np = "Percentage",
    cn = "n",
    cp = "Percentage",
    rn = "n",
    rp = "Percentage",
    int = "n",
    ip = "Percentage"
  ) |>
  tab_options(table.width = pct(100))
kbrevoort commented 2 months ago

Hi, @lokesh-krishna.

Yes, I think you're missing something. The way that Latex treats table widths can best be thought of as a minimum width. If you have 6 inches of space available between the margins and the table you're trying to print would naturally take 4 inches of space to display, Latex will add enough whitespace to to stretch the table to use all 6 inches of available space.

But if the table you're trying to print requires more than the available space (as is the case with the example you posted), then Latex will produce the overflow that you're observing. That's not something that I expect we'll be able to do anything to change.

The way to work around this is to provide Latex with guidance on how the table should be constrained. You could try changing font sizes, for example. In your case, I would make two small changes:

  1. When you specify the labels for np, cp, rp, and ip in the cols_label statement, I would shorten the label you're assigning. Instead of using "Percentage" use something shorter like "Pct."
  2. Explicitly tell Latex which column widths you want to constrain. (Importantly, table widths are treated as minimum widths, but column widths are treated as binding widths.)

For example, modifying your example to the following produced a table that did not create an overflow.

tribble(
  ~"HBV vaccination status", ~"rn", ~"rp", ~"nn", ~"np", ~"int", ~"ip", ~"cn", ~"cp",
  "Never vaccinated", 0, "0%", 0, "0%", 1, "5.8%", 0, "0%",
  "Discontinued", 5, "5.6%", 0, "0%", 2, "11.7%", 3, "2%",
  "All doses completed", 83, "94.4%", 101, "100%", 14, "82.5%", 145, "98%"
) |>
  gt() |>
  grand_summary_rows(
    columns = c("nn", "cn", "rn", "int"),
    fns = list(id = "total", label = "Totals", fn = "sum")
  ) |>
  tab_spanner(
    label = "Nursing Staff",
    columns = c("nn", "np")
  ) |>
  tab_spanner(
    label = "Class IV Employees",
    columns = c("cn", "cp")
  ) |>
  tab_spanner(
    label = "Resident Doctors",
    columns = c("rn", "rp")
  ) |>
  tab_spanner(
    label = "Interns",
    columns = c("int", "ip")
  ) |>
  cols_label(
    nn = "n",
    np = "Pct.",             # Note I've shortened the "Percentage" labels here
    cn = "n",
    cp = "Pct.",        
    rn = "n",
    rp = "Pct.",
    int = "n",
    ip = "Pct."
  ) |>
  cols_width(                                    # This is a new command
    seq(3, 9, by = 2) ~ pct(5),         # This constrains the "n" columns to be 5% of the available space each
    seq(4, 10, by = 2) ~ pct(10).      # This constrains the "Pct." columns to be 10% of the available space
  ) |>
  tab_options(table.width = pct(100))

Note that I'm specifying which widths I'm using the column numbers, not the names (i.e., nn, np). There's clearly a bug where when I tried to use the variable names, the widths of the wrong columns were changed. (Note to self, @kbrevoort revisit this bug.). Also, avoid any temptation in your example to try to set the widths of the stub columns (columns 1 and 2). I don't expect that you'll be able to improve on the unspecified widths for those columns.

Hope that helps.

lokesh-krishna commented 2 months ago

Thank you for such a patient and elaborate reply! Very grateful!