rstudio / gt

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

gt tables as grid tables - patchwork - only works if plot is on the left #1908

Open mm225022 opened 1 week ago

mm225022 commented 1 week ago

The gt tables as grid tables functionality is great.
However, it appears to only work if the plot is on the left, as per the example in the blog.

pizza_gtable <- 
    pizzaplace |>
    dplyr::filter(type %in% c("chicken", "supreme")) |>
    dplyr::group_by(type, size) |>
    dplyr::summarize(
        sold = dplyr::n(),
        income = sum(price),
        .groups = "drop"
    ) |>
    gt(
        rowname_col = "size",
        groupname_col = "type",
        row_group_as_column = TRUE
    ) |>
    tab_header(title = "Pizza Sales in 2015") |>
    fmt_integer(columns = sold) |>
    fmt_currency(columns = income) |>
    summary_rows(
        fns = list(label = "All Sizes", fn = "sum"),
        side = c("top"),
        fmt = list(
            ~ fmt_integer(., columns = sold),
            ~ fmt_currency(., columns = income)
        )
    ) |>
    grand_summary_rows(
        columns = c("sold", "income"),
        fns = Sum ~ sum(.),
        fmt = list(
            ~ fmt_integer(., columns = sold),
            ~ fmt_currency(., columns = income)
        )
    ) |>
    tab_options(summary_row.background.color = "gray98") |>
    tab_stub_indent(
        rows = everything(),
        indent = 2
    ) |>
    as_gtable()
pizza_plot <-
    pizzaplace |>
    dplyr::mutate(date = as.Date(date)) |>
    dplyr::filter(type %in% c("chicken", "supreme")) |>
    dplyr::group_by(date, type) |>
    dplyr::summarize(
        sold = dplyr::n(),
        .groups = "drop"
    ) |>
    ggplot() +
    geom_line(aes(x = date, y = sold, color = type, group = type)) +
    facet_wrap(~type, nrow = 2) +
    scale_x_date(date_labels = "%b", breaks = "1 month") +
    theme_minimal() +
    theme(legend.position = "none") +
    labs(x = "", y = "Pizzas Sold")
pizza_plot + pizza_gtable

This produces the graph and table side by side as per the blog

Question

However, if I reverse the order, and want the table on the left and the plot on the right, I get a NULL response and nothing is generated:

pizza_gtable + pizza_plot

gt grid table order

Is this intended functionality to only work in the specified order? If possible, I can envision sometimes wanting the chart on the left and the graph on the right.

olivroy commented 1 week ago

Hi! See also patchwork 1.3.0 release post. You can use patchwork::wrap_table().

So

patchwork::wrap_table(pizza_gtable) + pizza_plot