diff --git a/vignettes/accessibility_guide.Rmd b/vignettes/accessibility_guide.Rmd index ffe5a9cf..9d0e6da1 100644 --- a/vignettes/accessibility_guide.Rmd +++ b/vignettes/accessibility_guide.Rmd @@ -183,7 +183,7 @@ recruitment_alt_text <- new_alt_text 2. Edit figure and table captions with the same process. Just substitute mentions of alt text with caption. -3. As stated earlier, if you see text that looks like a placeholder (e.g., "The x axis, showing the year, spans from B.start.year to B.end.year..."), that means that there was at least one instance where our tool failed to extract a specific value from the model results and substitute it into the placeholder. Please make sure that your alt text and captions contain the expected values before moving forward with your report. Check out the inst/resources/captions_alt_text_template.csv file in the `stockplotr` package to view the template with placeholders. The same package's `write_captions()` function shows how values are extracted from the model results and substituted into the placeholders. +3. As stated earlier, if you see text that looks like a placeholder (e.g., "The x axis, showing the year, spans from B.start.year to B.end.year..."), that means that there was at least one instance where our tool failed to extract a specific value from the model results and substitute it into the placeholder. Please make sure that your alt text and captions contain the expected values before moving forward with your report. Check out the inst/resources/captions_alt_text_template.csv file in the `stockplotr` package to view the template with placeholders. 4. If you add a special character (e.g., percentage sign (%) or dollar sign ($); see [full list on this wiki page](https://en.wikibooks.org/wiki/LaTeX/Special_Characters#Other_symbols)), please add two backslashes before the character to avoid issues compiling your report later on (specifically, the conversion from Quarto to LaTeX via Pandoc, and then compilation of the LaTeX report after running `add_accessibility()` or `add_alttext()`). For example, "The 95% CI" would be written as "The 95\\\\% CI". diff --git a/vignettes/custom-figs-tabs.Rmd b/vignettes/custom-figs-tabs.Rmd index 4611b0ec..223d0dfc 100644 --- a/vignettes/custom-figs-tabs.Rmd +++ b/vignettes/custom-figs-tabs.Rmd @@ -3,11 +3,6 @@ title: "Adding Custom Tables and Figures" output: html_document: toc: true - toc_float: true - toc-depth: 3 - pdf_document: - toc: true - toc-depth: 3 vignette: > %\VignetteIndexEntry{Adding Custom Tables and Figures} %\VignetteEngine{knitr::rmarkdown} @@ -20,7 +15,7 @@ knitr::opts_chunk$set( comment = "#>" ) -library(flextable) +library(gt) ``` # Introduction @@ -29,865 +24,132 @@ The main way to create tables and figures for your `asar` report is by using fun ## Choose your workflow -### Comparing workflows - ```{r echo=F} data.frame( Option = c( - "1: direct image insertion workflow", + "1: Direct image insertion workflow", "2: rda-based workflow", - "3: direct coding-in-qmd workflow" + "3: Direct coding-in-qmd workflow" ), Summary = c( - "In this workflow, you will take minimal steps to add an external file to your report in this format: - - ![Your caption here](your_image.png){width=___in #fig-your_image_label_name}", - "In this workflow, you will make an rda containing your table/figure, caption, and alternative text, then add each into your report in the same way that non-custom tables/figures are added.", - "In this workflow, you will code, and plot, your table or figure directly in a Quarto document." + "Take minimal steps to add an external file to your report in this format:\n\n `![Your caption here](your_image.png){width=___in #fig-your_image_label_name}`", + "Make an rda containing your table/figure, caption, and alternative text, then add each into your report in the same way that non-custom tables/figures are added.", + "Code, and plot, your table or figure directly in a Quarto document." ), Appropriate_if = c( - "- You don't need to package your table/figure, caption, and alternative text in a single file\n - -- Your table/figure is already saved as an external file (e.g., a png)\n - -- Each table/figure is at most 8\" wide, or can be shrunken to 8\" wide and still be legible", + "- You don't need to package your table/figure, caption, and alternative text in a single file\n\n- Your table/figure is already saved as an external file (e.g., a png)\n\n- Each table/figure is at most 8\" wide, or can be shrunken to 8\" wide and still be legible", "- You'd like to create and save your custom tables/figures in a manner that's most consistent with your other tables/figures generated with asar's complementary R package, stockplotr", - "- You don't need to package your table/figure, caption, and alternative text in a single file\n - -- You don't need to export your table/figure\n - -- Each table/figure is at most 8\" wide, or can be shrunken to 8\" wide and still be legible)" + "- You don't need to package your table/figure, caption, and alternative text in a single file\n\n- You don't need to export your table/figure\n\n- Each table/figure is at most 8\" wide, or can be shrunken to 8\" wide and still be legible)" ), Pros = c( "- Faster process than option 2", - "- More reproducible\n - -- Saves and stores custom tables/figures in a way that mirrors existing tables/figures generated with stockplotr", - "- Faster process than option 2\n - -- Not necessary to import any files to display a table/figure" + "- More reproducible\n\n- Saves and stores custom tables/figures in a way that mirrors existing tables/figures generated with stockplotr", + "- Faster process than option 2\n\n- Not necessary to import any files to display a table/figure" ), Cons = c( - "- Less reproducible\n - -- Files (i.e., table/figure, caption, and alternative text) aren't saved in a consistent and predictable system\n - -- Captions and alternative text aren't saved with other figures'/tables' texts\n - -- Table text is not machine-readable, creating a barrier for accessibility", + "- Less reproducible\n\n- Files (i.e., table/figure, caption, and alternative text) aren't saved in a consistent and predictable system\n\n- Captions and alternative text aren't saved with other figures'/tables' texts\n\n- Table text is not machine-readable, creating a barrier for accessibility", "- Slower process than options 1 & 3", - "- Less reproducible\n - -- Files (i.e., table/figure, caption, and alternative text) aren't exported, and therefore not saved in a consistent and predictable system\n - -- Captions and alternative text aren't saved with other figures'/tables' texts" + "- Less reproducible\n\n- Files (i.e., table/figure, caption, and alternative text) aren't exported, and therefore not saved in a consistent and predictable system\n\n- Captions and alternative text aren't saved with other figures'/tables' texts" ) ) |> - flextable::flextable() |> - flextable::border_inner(part = "all") |> - flextable::align( - part = "header", - align = "center" + gt() |> + fmt_markdown(columns = everything()) |> + tab_header( + title = md("**Workflow Options for Custom Tables and Figures**") ) |> - flextable::set_header_labels("Appropriate_if" = "Appropriate if...") |> - flextable::bold(part = "header") |> - flextable::set_caption(caption = "Workflow options for adding custom tables and figures to your report.") |> - flextable::autofit() -``` - -### Main steps in each workflow - -#### Direct image insertion workflow (option 1) - -1. [Write captions and alternative text](#sec-write-caps-alttext) -2. [Set up Quarto markdown (.qmd) files to display custom tables and figures](#sec-set-up-qmd) -3. [Update report skeleton](#sec-update-skeleton) - -#### rda-based workflow (option 2) {#rda-based-workflow-option-2} - -1. [Code your custom tables and figures] -2. [Write captions and alternative text](#sec-write-caps-alttext) -3. [Export your custom tables and figures] -4. [Identify table width, orientation, and if splitting is necessary](#sec-id_width) -5. [Set up Quarto markdown (.qmd) files to display custom tables and figures](#sec-set-up-qmd) -6. [Update report skeleton](#sec-update-skeleton) - -#### Direct coding-in-qmd workflow (option 3) - -1. [Code your custom tables and figures] -2. [Write captions and alternative text](#sec-write-caps-alttext) -3. [Identify table width, orientation, and if splitting is necessary](#sec-id_width) -4. [Set up Quarto markdown (.qmd) files to display custom tables and figures](#sec-set-up-qmd) -5. [Update report skeleton](#sec-update-skeleton) - -# Code your custom tables and figures - -*Using the direct image insertion workflow (option 1)? Skip this step and proceed to the* [Write captions and alternative text](#sec-write-caps-alttext) *section.* - -First, write the code to produce (but not export; that's a future step!) your custom tables and figures. Save each table and figure as an object (e.g., in the examples below, `your_table` and `your_figure`). Save the script somewhere safe. - -```{r eval=F} -# Example dataframe -your_df <- data.frame( - "x" = c(1, 2, 3), - "y" = c(4, 5, 6) -) - -# Example table -your_table <- flextable::flextable(your_df) - -# Example figure -your_figure <- ggplot2::ggplot( - your_df, - aes( - x = x, - y = y - ) -) + - ggplot2::geom_point() -``` - -# Write captions and alternative text {#sec-write-caps-alttext} - -Next, once you know what your tables and figures look like, write your own captions and alternative text. Custom tables will require captions only. - -## Writing text - -Check out the `stockplotr` ['captions_alt_text_template.csv' file](https://github.com/nmfs-ost/stockplotr/blob/master/inst/resources/captions_alt_text_template.csv), which contains the templates for each table or figure's caption/alternative text, to get a sense of how each description is structured. Then, refer to [the accessibility vignette's guide](https://nmfs-ost.github.io/asar/articles/accessibility_guide.html) to learn how to write clear and comprehensive alternative text. - -We recommend adding in key quantities, like maximum and minimum values, to ensure your captions and alternative text clearly describe your plots. For example, if you're showing how biomass changed over time, we recommend providing the maximum and minimum values of biomass and years shown, instead of simply stating that a figure shows biomass changing over time. Check out the code within [the `stockplotr::write_captions()` function](https://github.com/nmfs-ost/stockplotr/blob/master/R/write_captions.R) to see how we extract certain key quantities from the model results files. You are welcome to use and adapt that code to your own results to calculate key quantities, or calculate the quantities with your own code. - -## Saving text - -*Using the direct coding-in-qmd workflow (option 3)? Skip this step and proceed to [Identify table width, orientation, and if splitting is necessary](#sec-id_width).* - -Once written, you'll have to save your captions and alternative text. - -Do you have an existing captions_alt_text.csv file? If you've already generated a figure or table rda, this file should exist, most likely in your working directory. If you don't have one, run `stockplotr::write_captions()` or another `stockplotr` plotting function (e.g., `plot_biomass()`, `table_bnc()`) to generate the file. - -Open captions_alt_text.csv file, then add your text. The file is set up like this: - -- Column 1 ("label") is a shorthand label for your figure or table. Labels should be somewhat short and exclude spaces. Examples include "kobe", "relative.biomass", and "fishing.mortality". -- Column 2 ("type") contains "figure" or "table". -- Column 3 ("caption") contains your caption. -- Column 4 ("alt_text") contains alternative text for figures. For tables, this column will be blank. - -+-------------+------------+-----------------------------+--------------------------------------+ -| label | type | caption | alt_text | -+=============+============+=============================+======================================+ -| example_fig | figure | Example caption for figure. | Example alternative text for figure. | -+-------------+------------+-----------------------------+--------------------------------------+ -| example_tab | table | Example caption for table. | | -+-------------+------------+-----------------------------+--------------------------------------+ - -: Format for csv containing table and figure captions and alternative text. - -> **NOTE**: If you are using the direct image insertion workflow (option 1), only the _alternative text_ will be used in your final report- not the caption. This happens because of the workaround workflow that allows us to add alt text into PDFs. The caption will be taken from your directly-coded image's markdown code, so you can leave it empty or put the same caption here; it doesn't matter. - -# Export your custom tables and figures - -*Using the direct image insertion workflow (option 1)? Skip this step and proceed to [Set up Quarto markdown (.qmd) files to display custom tables and figures](#sec-set-up-qmd).* - -Next, export your tables and figures to rda files. This code was adapted from functions like `stockplotr::plot_biomass`. - -## Import pre-written captions and alternative text - -Import your csv containing your captions and alternative text and save it as an object. Then, save the captions and alternative text as separate objects. For example: - -```{r eval=F} -# Import captions and alternative text -my_text <- read.csv(file = "captions_alt_text.csv") - -# Extract table caption -my_table_cap <- my_text |> - dplyr::filter( - label == "example_table", - type == "table" + cols_label( + Appropriate_if = "Appropriate if...", + Option = "Workflow" ) |> - dplyr::select(caption) |> - as.character() - -# Extract figure caption -my_figure_cap <- my_text |> - dplyr::filter( - label == "example_fig", - type == "figure" + cols_width( + Option ~ px(140), + Summary ~ px(220), + Appropriate_if ~ px(240), + Pros ~ px(200), + Cons ~ px(240) ) |> - dplyr::select(caption) |> - as.character() - -# Extract figure alternative text -my_figure_alt_text <- my_text |> - dplyr::filter( - label == "example_fig", - type == "figure" + cols_align(align = "left", columns = everything()) |> + tab_style( + style = cell_text(weight = "bold", size = px(14)), + locations = cells_column_labels() ) |> - dplyr::select(alt_text) |> - as.character() -``` - -> **NOTE**: Your label must match the label associated with your table or figure in your csv containing the captions and alternative text. If it does not match, the label will not be extracted properly and added to your rdas. - -## Make rdas - -Your rdas will contain your table or figure, caption, and alternative text (if it's a figure). - -### Tables - -```{r eval=F} -rda <- list( - "table" = your_table, # your table object - "caption" = my_table_cap # your table caption -) -``` - -### Figures - -```{r eval=F} -rda <- list( - "figure" = your_figure, # your figure object - "caption" = my_figure_cap, # your figure caption - "alt_text" = my_figure_alt_text # your figure alternative text -) -``` - -## Make 'figures' and 'tables' folders (if needed) - -Do you already have 'figures' and 'tables' folders? *Hint: both should be in your working directory.* If yes: Great! You can skip this step. If not, simply enter the code below to make a the folders. - -```{r eval=FALSE} -dir.create(fs::path(getwd(), "figures")) -dir.create(fs::path(getwd(), "tables")) -``` - -## Export your rdas - -### Tables - -This will produce an rda called "example_tab.rda" and save it in your 'tables' folder. - -```{r eval=FALSE} -save(rda, - file = fs::path( - getwd(), # this is your tables directory - "tables", - paste0( - "example_tab.rda" # your table's label - ) - ) -) -``` - -### Figures - -This will produce an rda called "example_fig.rda" and save it in your 'figures' folder. - -```{r eval=FALSE} -save(rda, - file = fs::path( - getwd(), # this is your figures directory - "figures", - paste0( - "example_fig.rda" # your figure's label - ) + tab_style( + style = cell_text(weight = "bold", color = "#333333"), + locations = cells_body(columns = Option) + ) |> + opt_row_striping() |> + tab_options( + table.width = px(1040), + data_row.padding = px(10), + table.border.top.style = "none", + table_body.hlines.color = "#eeeeee", + column_labels.border.bottom.color = "#333333", + column_labels.border.bottom.width = px(2) ) -) -``` - -# Identify table width, orientation, and if splitting is necessary {#sec-id_width} - -*Skip this section if you are not including custom tables.* - -Your next step is to get a sense of your table dimensions. You'll ask: - -- Will each fit neatly into a portrait orientation, or should the page be rotated 90 degrees into landscape view? -- Even in landscape view, is the table too wide to be shown properly, and must be split into smaller tables? - -This section contains the steps to answer these questions. - -> **NOTE**: This workflow is reflected in the create_tables_doc.R file and its associated functions (such as `render_lg_table()`, `ID_tbl_width_class()` and `export_split_tbls()`). - -## Table width and orientation - -### rda-based workflow (option 2) {#sec-tbl-width-op2} - -Run this code: - -```{r eval=F} -my_plot_name <- "example_tab.rda" # replace this with the filename of your table rda -tables_dir <- getwd() # replace this with the location of your tables folder - -ID_tbl_width_class( - plot_name = my_plot_name, - tables_dir = tables_dir, - portrait_pg_width = 5 # 5 inches = the threshold for maximum table width before it needs to be resized, rotated, and/or split -) -``` - -You will see one of three outputs: regular, wide, or extra-wide. - -+--------------------+:------------:+:-------------------------:+:------------:+ -| **Classification** | Regular | Wide | Extra-wide | -+--------------------+--------------+---------------------------+--------------+ -| **Table width** | \< 5" | at least 5" and up to 12" | \>12" | -+--------------------+--------------+---------------------------+--------------+ - -: Table width classification system coded in the `ID_tbl_width_class` function. - -*If your output is regular*, this means that you can display your table in a .qmd chunk without any additional steps. Jump to section [Set up Quarto markdown (.qmd) files to display custom tables and figures](#sec-set-up-qmd) and proceed. - -*If your output is wide*, this means that you will place your table's .qmd chunk in special braces that change the page orientation to landscape. Jump to section [Set up Quarto markdown (.qmd) files to display custom tables and figures](#sec-set-up-qmd) and proceed. - -*If your output is extra-wide*, this means that you will place your table's .qmd chunk in special braces that change the page orientation to landscape *and* split it into narrower tables, each of which are displayed on separate pages. Proceed to the section [Table splitting (for extra-wide tables only)](#sec-table-splitting). - -### Direct coding-in-qmd workflow (option 3) - -Assuming your table is saved as a flextable, run this code: - -```{r eval=F} -# assuming your flextable object is called my_flextable - -flextable::flextable_dim(my_flextable)[["widths"]] |> - as.numeric() -``` - -Refer to the table above in above section ([rda-based workflow (option 2)](#rda-based-workflow-option-2)) to find out which category best describes your table width: regular, wide, or extra-wide. - -*If your table is regular or wide*, read the text below the table and jump to the appropriate section. - -*If your table is extra-wide*, please start over and use the rda-based workflow. This workflow is not built for the extra steps needed to split an extra-wide table into multiple smaller tables. - -## Table splitting (for extra-wide tables only) {#sec-table-splitting} - -Extra-wide tables will need to be split among multiple pages. Run this code to learn the number of tables into which your original table will be split *and* export the split tables (as a list) into a new rda: - -```{r eval=F} -my_plot_name <- "example_tab.rda" # replace this with the filename of your table rda -tables_dir <- getwd() # replace this with the location of your tables folder -essential_cols <- 1:2 # replace this with the columns that will be retained between the split tables, formatted as a sequence (e.g., 1:2 for columns 1-2, or 1 for a single column) - -export_split_tbls( - tables_dir = tables_dir, - plot_name = my_plot_name, - essential_columns = essential_cols -) -``` - -If the number returned was, say, 5, then since each split table must be in its own chunk, you will need 5 chunks to show your split tables. You will also need an additional chunk to load in the data. Each table needs its own chunk, and therefore label, so that it can be cross-referenced in text. - -You can check out your split tables in the new rda saved in your tables_dir folder. It will have the same filename as your original rda except that it will contain "\_split" in the filename. For instance, split tables created from "example_tab.rda" will be saved in "example_tab_table_split.rda". - -# Set up Quarto markdown (.qmd) files to display custom tables and figures {#sec-set-up-qmd} - -You will create one .qmd file for your tables and one .qmd file for your figures. - -## Set up templates - -Open a blank .qmd script (in RStudio, click File -\> New File -\> Quarto Document -\> Create Empty Document (button in the bottom left corner of the popup)). - -Remove all text from the new document. - -Switch from Visual to Source mode ([instructions here](https://quarto.org/docs/visual-editor/#switching-modes)). - -Save this new file with a clear name in a logical location. We recommend filenames like 08_tables_custom.qmd and 09_figures_custom.qmd, then saving these files in the same report folder as the rest of your report files. We include separate workflows for tables and figures, below. - -### Direct image insertion workflow (option 1) - -#### Identify page orientation - -If you're using this workflow, your table/figure should be at most 8" wide or can be shrunken to 8" wide and still be legible. Find the width of your image file. Would you prefer to show it on a page with a portrait orientation (can fit 5" width) or landscape orientation (can fit 8" width)? - -Identify the preferred width of your image. Keep it in mind for when you add your image in the next section. - -#### Add image - -Next, add your image in this format ([see this Quarto documentation for more information](https://quarto.org/docs/authoring/figures.html)): - -``` markdown -![Your caption here](your_image.png){width=___in #fig-your_image_label_name} ``` -> **NOTE**: Remember that alternative text placed in this markdown format will not be put into your final report file; it must be in the captions_alt_text.csv file. However, *you must put the caption here*. -> **NOTE**: It can be a headache to specify the correct image path. We recommend placing your files in either of these places: -1. Your report folder (path = the image name, like *image.png*) -2. A folder within your report folder (path = the relative filepath, like *images/image.png* if there's an images folder within report) +# Workflow Guides {.tabset .tabset-fade .tabset-pills} -Here are some examples, using the following example folder structure setup: +## Direct image insertion workflow (option 1) -``` markdown -stock_assessments_2025/ -├── captions_alt_text.csv -├── report/ -│ ├── 01_executive_summary.qmd -│ ├── 02_introduction.qmd -│ ├── my_custom_figure.png -│ ├── images/ -│ │ ├── my_custom_table.png -``` +1. Write captions and alternative text +2. Save captions and alternative text +3. Add custom tables and figures -``` markdown -# Example 1 -![Here is my caption to my example figure.](my_custom_figure.png){width=3in #fig-custom_figure1} +```{r, child="snippets/write-caps-alttext.Rmd"} ``` -``` markdown -# Example 2 -![Here is my caption to my example table.](images/my_custom_table.png){width=5in #fig-custom_table1} +```{r, child='snippets/save-caps-alttext.Rmd'} ``` -#### Add landscape braces (optional) +> **NOTE**: Only the _alternative text_ will be used in your final report- not the caption. This happens because of the workaround workflow that allows us to add alt text into PDFs. The caption will be taken from your directly-coded image's markdown code, so you can leave it empty or put the same caption here; it doesn't matter. -If you'd like to place your image on a landscape-oriented page, you'll add [landscape braces](https://quarto.org/docs/authoring/article-layout.html#landscape-mode) before and after your table/figure to ensure it will be displayed properly, like this: - -```{verbatim} -::: {.landscape} +```{r, child="snippets/add-plots_img.Rmd"} ``` -``` rmd -![Your caption here](your_image.png){width=___in #fig-your_image_label_name} -``` +## rda-based workflow (option 2) {#rda-based-workflow-option-2} -Then, add three colons to close the braces: +1. Code your custom tables and figures +2. Write captions and alternative text +3. Save captions and alternative text +4. Export your custom tables and figures +5. Identify table width, orientation, and if splitting is necessary +6. Add custom tables and figures -```{verbatim} -::: +```{r, child="snippets/code-custom-figs-tables.Rmd"} ``` -> **NOTE**: Landscape braces only work in [Quarto v1.6+](https://quarto.org/docs/blog/posts/2024-11-25-1.6-release/). Please read [this Discussion](https://github.com/nmfs-ost/asar/discussions/186) to learn how to check your Quarto version and update it if necessary. - -#### Page break - -If you are including more than one custom table or figure in a file, we suggest adding a page break to separate the tables/figures: - -```{verbatim} -{{< pagebreak >}} +```{r, child='snippets/write-caps-alttext.Rmd'} ``` -You're almost done! Proceed to the last section ([Update report skeleton](#sec-update-skeleton)) to finish adding your custom tables to your report. - -### rda-based workflow (option 2) - -#### Tables - -In your tables doc, add your first R chunk (shown below). This chunk is used to establish your tables_dir folder and load the library needed to plot your tables (`flextable`). - -Click the following links to learn more about [cross-references](https://quarto.org/docs/computations/execution-options.html) (label) and [chunk options](https://quarto.org/docs/computations/execution-options.html) (echo, warning, etc.). - -````{verbatim} -```{r} -#| label: 'set-rda-dir-tbls-custom' # you can set this label as you wish, as long as it's not repeated in any other R chunk in, for instance, the 08_tables.qmd or 09_figures.qmd files. Labels are used for cross-referencing in your report text. -#| echo: false -#| warning: false -#| include: false -library(flextable) -tables_dir <- "C:/path/to/your/tables" # set the path to your tables_dir -``` -```` - -Now, follow the instructions in the appropriate section depending on your table width: regular, wide, or extra wide. - -##### Regular table - -Add the following chunk to your script to import your table's rda and save objects containing the table and caption: - -````{verbatim} -```{r} -#| label: 'tbl-setup-custom1' # choose a label -#| echo: false -#| warning: false -#| include: false -# load your rda and save with a table-specific name, then delete "rda" -load(file.path(tables_dir, "example_tab.rda")) -example_table_rda <- rda -rm(rda) - -# save table, caption as separate objects -example_table <- example_table_rda$table -example_cap <- example_table_rda$caption -``` -```` - -Then, add this chunk to display the table in your .qmd when it's rendered: - -````{verbatim} -```{r} -#| label: 'tbl-custom1' # choose a label -#| echo: false -#| warning: false -#| tbl-cap: !expr example_cap -example_table -``` -```` - -If you are adding another table, regardless of size, add a page break first: - -```{verbatim} -{{< pagebreak >}} +```{r, child='snippets/save-caps-alttext.Rmd'} ``` -Keep adding as many tables as you'd like. Keep in mind that each table must have a chunk that imports it, and another chunk that displays it, as shown above. - -You're almost done! Proceed to the last section ([Update report skeleton](#sec-update-skeleton)) to finish adding your custom tables to your report. - -##### Wide table - -Add the following chunk to your script to import your table's rda and save objects containing the table and caption: - -````{verbatim} -```{r} -#| label: 'tbl-setup-custom1' # choose a label -#| echo: false -#| warning: false -#| include: false -# load your rda and save with a table-specific name, then delete "rda" -load(file.path(tables_dir, "example_tab.rda")) -example_table_rda <- rda -rm(rda) - -# save table, caption as separate objects -example_table <- example_table_rda$table -example_cap <- example_table_rda$caption -``` -```` - -Before you add your next chunk, add [landscape braces](https://quarto.org/docs/authoring/article-layout.html#landscape-mode) to ensure your table will be displayed on a landscape-oriented page: - -```{verbatim} -::: {.landscape} +```{r, child='snippets/export-custom-figs-tables.Rmd'} ``` -Then, add this chunk to display the table in your .qmd when it's rendered: - -````{verbatim} -```{r} -#| label: 'tbl-custom1' # choose a label -#| echo: false -#| warning: false -#| tbl-cap: !expr example_cap -example_table |> - flextable::fit_to_width(max_width = 8) # this extra line ensures the table will be resized to a maximum of 8" wide -``` -```` - -And add three colons to close the landscape braces: - -```{verbatim} -::: +```{r, child='snippets/id_width.Rmd'} ``` -> **NOTE**: Landscape braces only work in [Quarto v1.6+](https://quarto.org/docs/blog/posts/2024-11-25-1.6-release/). Please read [this Discussion](https://github.com/nmfs-ost/asar/discussions/186) to learn how to check your Quarto version and update it if necessary. - -If you are adding another table, regardless of size, add a page break first: - -```{verbatim} -{{< pagebreak >}} +```{r, child='snippets/add-plots_rda.Rmd'} ``` -Keep adding as many tables as you'd like. Keep in mind that each table must have a chunk that imports it, and another chunk that displays it, as shown above. - -You're almost done! Proceed to the last section ([Update report skeleton](#sec-update-skeleton)) to finish adding your custom tables to your report. - -##### Extra-wide table - -Add the following chunk to your script to: - -- import your *original table's* rda -- save original table's caption as a separate object -- import your *split tables'* rda -- save split tables' caption specifiers as a separate object - -````{verbatim} -```{r} -#| label: 'tbl-labels-custom1' # choose a label -#| echo: false -#| warning: false -#| include: false -# load your original table rda and save with a table-specific name, then delete "rda" -load(file.path(tables_dir, "example_tab.rda")) -example_table_rda <- rda -rm(rda) - -# save caption as separate object -example_cap <- example_table_rda$caption - -# load split table rda and save with a table-specific name, then delete "table_list" -load(file.path(tables_dir, "example_table_split.rda")) -example_table_rda_split <- table_list -rm(table_list) - -# extract table caption specifiers -example_cap_split <- names(example_table_rda_split) -``` -```` - -Example caption specifiers could include fleets only shown in specific tables. +## Direct coding-in-qmd workflow (option 3) -Before you add your next chunk, add [landscape braces](https://quarto.org/docs/authoring/article-layout.html#landscape-mode) to ensure your table will be displayed on a landscape-oriented page: +1. Code your custom tables and figures +2. Write captions and alternative text +3. Identify table width, orientation, and if splitting is necessary +4. Add custom tables and figures -```{verbatim} -::: {.landscape} +```{r, child="snippets/code-custom-figs-tables.Rmd"} ``` -Now, you'll add as many chunks as you have split tables. Here's what the first one will look like: - -````{verbatim} -```{r} -#| label: 'tbl-custom1' # choose a label -#| echo: false -#| warning: false -#| tbl-cap: !expr paste0(example_cap, '(', example_cap_split[[1]], ')') # this pastes the original table caption with the specifiers associated with table 1 - -# plot split table 1 -example_table_rda_split[[1]] |> - flextable::fit_to_width(max_width = 8) # this extra line ensures the table will be resized to a maximum of 8" wide -``` -```` - -Copy and paste this chunk for as many split tables as you have. Then, replace the instances of "1" with the split table number (e.g., 2,3,4, etc.). In the example above, "1" occurs in the chunk options (label, tbl-cap) and the table-plotting code itself. - -Now, add three colons to close the landscape braces: - -```{verbatim} -::: +```{r, child='snippets/write-caps-alttext.Rmd'} ``` -> **NOTE**: Landscape braces only work in [Quarto v1.6+](https://quarto.org/docs/blog/posts/2024-11-25-1.6-release/). Please read [this Discussion](https://github.com/nmfs-ost/asar/discussions/186) to learn how to check your Quarto version and update it if necessary. - -Keep adding as many tables as you'd like. Keep in mind that each table must have a chunk that imports it, and another chunk that displays it, as shown above. - -You're almost done! Proceed to the last section ([Update report skeleton](#sec-update-skeleton)) to finish adding your custom tables to your report. - -#### Figures - -The workflow for figures is very similar to the workflow for regular tables. - -In your figures doc, add your first R chunk (shown below). This chunk is used to establish your figures_dir folder. - -Click the following links to learn more about [cross-references](https://quarto.org/docs/computations/execution-options.html) (label) and [chunk options](https://quarto.org/docs/computations/execution-options.html) (echo, warning, etc.). - -````{verbatim} -```{r} -#| label: 'set-rda-dir-figs-custom' # you can set this label as you wish, as long as it's not repeated in any other R chunk in, for instance, the 08_tables.qmd or 09_figures.qmd files. Labels are used for cross-referencing in your report text. -#| echo: false -#| warning: false -figures_dir <- "C:/path/to/your/figures" # set the path to your figures_dir -``` -```` - -Add the following chunk to your script to import your figure's rda and save objects containing the figure, caption, and alternative text: - -````{verbatim} -```{r} -#| label: 'fig-setup-custom1' # choose a label -#| echo: false -#| warning: false -#| include: false -# load your rda and save with a figure-specific name, then delete "rda" -load(file.path(figures_dir, "example_fig.rda")) -example_figure_rda <- rda -rm(rda) - -# save figure, caption, and alternative text as separate objects -example_plot <- example_figure_rda$figure -example_cap <- example_figure_rda$caption -example_alt_text <- example_figure_rda$alt_text -``` -```` - -Then, add this chunk to display the figure in your .qmd when it's rendered: - -````{verbatim} -```{r} -#| label: 'fig-custom1' # choose a label -#| echo: false -#| warning: false -#| fig-cap: !expr example_cap -#| fig-alt: !expr example_alt_text -example_plot -``` -```` - -If you are adding another figure, add a page break first: - -```{verbatim} -{{< pagebreak >}} -``` - -You're almost done! Proceed to the last section ([Update report skeleton](#sec-update-skeleton)) to finish adding your custom figures to your report. - -### Direct coding-in-qmd workflow (option 3) - -#### Tables - -Follow the instructions in the appropriate section depending on your table width: regular or wide. - -##### Regular table - -Add the following chunk to display the table in your .qmd when it's rendered: - -````{verbatim} -```{r} -#| label: 'tbl-custom1' # choose a label -#| echo: false -#| warning: false -#| tbl-cap: !expr This is your table caption. - -# Import your data -your_df <- data.frame( - "x" = c(1, 2, 3), - "y" = c(4, 5, 6) -) - -# Make your table -your_table <- flextable::flextable(your_df) - -# Show your table -your_table -``` -```` - -If you are adding another table, regardless of size, add a page break first: - -```{verbatim} -{{< pagebreak >}} -``` - -Keep adding as many tables as you'd like. Keep in mind that each table must have a chunk that imports it, and another chunk that displays it, as shown above. - -You're almost done! Proceed to the last section ([Update report skeleton](#sec-update-skeleton)) to finish adding your custom tables to your report. - -##### Wide table - -Before you add your first chunk, add [landscape braces](https://quarto.org/docs/authoring/article-layout.html#landscape-mode) to ensure your table will be displayed on a landscape-oriented page: - -```{verbatim} -::: {.landscape} -``` - -Then, add the following chunk to display the table in your .qmd when it's rendered: - -````{verbatim} -```{r} -#| label: 'tbl-custom1' # choose a label -#| echo: false -#| warning: false -#| tbl-cap: !expr This is your table caption. - -# Import your data -your_df <- data.frame( - "x" = c(1, 2, 3), - "y" = c(4, 5, 6) -) - -# Make your table -your_table <- flextable::flextable(your_df) |> - flextable::fit_to_width(max_width = 8) # this extra line ensures the table will be resized to a maximum of 8" wide - -# Show your table -your_table -``` -```` - -And add three colons to close the landscape braces: - -```{verbatim} -::: +```{r, child='snippets/id_width.Rmd'} ``` -> **NOTE**: Landscape braces only work in [Quarto v1.6+](https://quarto.org/docs/blog/posts/2024-11-25-1.6-release/). Please read [this Discussion](https://github.com/nmfs-ost/asar/discussions/186) to learn how to check your Quarto version and update it if necessary. - -If you are adding another table, regardless of size, add a page break first: - -```{verbatim} -{{< pagebreak >}} +```{r, child='snippets/add-plots_coding.Rmd'} ``` - -Keep adding as many tables as you'd like. Keep in mind that each table must have a chunk that imports it, and another chunk that displays it, as shown above. - -You're almost done! Proceed to the last section ([Update report skeleton](#sec-update-skeleton)) to finish adding your custom tables to your report. - -#### Figures - -The workflow for figures is very similar to the workflow for regular tables. - -In your figures doc, add the following chunk to display the figure in your .qmd when it's rendered: - -````{verbatim} -```{r} -#| label: 'fig-custom1' # choose a label -#| echo: false -#| warning: false -#| fig-cap: !expr This is your figure caption. -#| fig-alt: !expr This is your figure alternative text. -# Import your data -your_df <- data.frame( - "x" = c(1, 2, 3), - "y" = c(4, 5, 6) -) - -# Make your figure -your_figure <- ggplot2::ggplot( - your_df, - aes( - x = x, - y = y - ) -) + - ggplot2::geom_point() - -# Show your figure -your_figure -``` -```` - -If you are adding another figure, add a page break first: - -```{verbatim} -{{< pagebreak >}} -``` - -You're almost done! Proceed to the last section ([Update report skeleton](#sec-update-skeleton)) to finish adding your custom figures to your report. - -# Update report skeleton {#sec-update-skeleton} - -Finally, the last step is to update the report skeleton so that it imports your new custom table and figure .qmd files. - -Open your skeleton .qmd file. Scroll down to the chunks that contain tables and figures (their labels are "tables" and "figures", respectively). - -Your "tables" chunk will look similar, if not identical, to this: - -````{verbatim} -```{r, results='asis'} -#| label: 'tables' -#| eval: true -#| echo: false -#| warning: false -a <- knitr::knit_child("08_tables.qmd", quiet = TRUE) -cat(a, sep = "\n") -``` -```` - -If you are adding custom tables, copy the two lines of code that start with "a \<- knitr::" and "cat". Paste them below the original two lines of code in the same chunk. Then, in those two new lines, make the following changes: - -1. Change "a" to "b" -2. Replace '08_tables.qmd' with the name of your new custom .qmd - -For example: - -````{verbatim} -```{r, results='asis'} -#| label: 'tables' -#| eval: true -#| echo: false -#| warning: false -a <- knitr::knit_child("08_tables.qmd", quiet = TRUE) -cat(a, sep = "\n") -b <- knitr::knit_child("08_tables_custom.qmd", quiet = TRUE) -cat(b, sep = "\n") -``` -```` - -If you're adding custom figures, follow the same steps with the figures chunk. - -Save the changes to your skeleton, and you're done! Your custom tables and figures will be included in your report. diff --git a/vignettes/snippets/add-plots_coding.Rmd b/vignettes/snippets/add-plots_coding.Rmd new file mode 100644 index 00000000..81ed30cc --- /dev/null +++ b/vignettes/snippets/add-plots_coding.Rmd @@ -0,0 +1,207 @@ +### Add custom tables and figures {#sec-add-plots_coding} + +In your 'report' folder, open your figures and tables docs (probably named something like '08_tables.qmd' and '09_figures.qmd'). Add the following code there. + +**IMPORTANT**: The label in your captions/alt text csv must match the label in your plot's chunk options, **MINUS the "fig-" or "tab-"**. For example, the label "custom_table1" in the csv would match up properly with the "tbl-custom_table1" label in a code chunk. +The same rule applies for figures: "custom_figure1" in the csv would match up with "fig-custom_figure1" in the chunk options' label. + +#### Tables + +Follow the instructions in the appropriate section below based on your table classification: reg_reg, reg_long, wide_reg, wide_long, ewide_reg, or ewide_long. + +For all table types, add a setup chunk to define your table and its caption: + +````{verbatim} +```{r} +#| label: 'tab-setup-custom' +#| include: false + +# Example dataframe +your_df <- data.frame( + "x" = c(1, 2, 3), + "y" = c(4, 5, 6) +) + +# Example table +your_table <- gt::gt(your_df) + +# Define your caption +your_cap <- "This is the caption for my custom table." +``` +```` + +##### Regular tables (`reg_reg`) + +*Portrait orientation, fits on one page.* + +Add this chunk to display the table: + +````{verbatim} +```{r} +#| label: 'tbl-custom1' +#| echo: false +#| warning: false +#| tbl-cap: !expr your_cap + +your_table +``` +```` + +##### Wide tables (`wide_reg`) + +*Landscape orientation, fits on one page.* + +Wrap the chunk in landscape braces: + +````{verbatim} +::: {.landscape} + +```{r} +#| label: 'tbl-custom-wide' +#| echo: false +#| warning: false +#| tbl-cap: !expr your_cap + +your_table |> + gt::tab_options(table.width = pct(100), table.layout = 'auto') |> + gt::cols_width(everything() ~ pct(20)) +``` + +::: +```` + +##### Long tables (`reg_long` or `wide_long`) + +*Splits by row across multiple pages. `wide_long` uses landscape; `reg_long` uses portrait.* + +You will need a separate chunk for each page of the split. For example, if your table requires 2 pages, repeat this chunk twice, changing the index in `grp_pull(1)` to `grp_pull(2)`. + +````{verbatim} +```{r} +#| label: 'tbl-custom-long-p1' +#| echo: false +#| tbl-cap: !expr paste0(your_cap, ' (Page 1 of 2)') + +your_table |> + gt::tab_options(table.width = pct(100), table.layout = 'auto') |> + gt::cols_width(everything() ~ pct(20)) |> + asar::gt_split(row_every_n = 38) |> # Use 28 for wide_long + gt::grp_pull(1) # Change this to 2 for the next page +``` +```` + +> **NOTE**: For `wide_long`, wrap the chunk in `::: {.landscape}` braces. For example: + +````{verbatim} +::: {.landscape} +# code chunk shown above +::: +```` + +##### Extra-wide tables (`ewide_reg`) + +*Landscape orientation, split by column across multiple pages.* + +Because extra-wide tables are split by column, you must have already run `export_split_tbls()` to create the `_split.rda` file. Load that split file to access the list of tables: + +````{verbatim} +```{r} +#| label: 'tbl-setup-ewide-split' +#| include: false +# Load the list of split tables generated by export_split_tbls() +load(file.path(tables_dir, 'example_tab_table_split.rda')) +table_list_split <- table_list +``` +```` + +Then, for each split table in the list, create a landscape chunk: + +````{verbatim} +::: {.landscape} + +```{r} +#| label: 'tbl-custom-ewide-c1' +#| echo: false +#| tbl-cap: !expr paste0(your_cap, ' (Column split 1 of 3)') + +table_list_split[[1]] |> + gt::tab_options(table.width = pct(100), table.layout = 'auto') |> + gt::cols_width(everything() ~ pct(20)) +``` + +::: +```` + +##### Extra-wide, long tables (`ewide_long`) + +*Landscape orientation, split by both column AND row.* + +This requires a nested approach using the `table_list_split` loaded above. You must create chunks for every combination of column-split and row-split. + +````{verbatim} +::: {.landscape} + +```{r} +#| label: 'tbl-custom-ewide-long-c1-r1' +#| echo: false +#| tbl-cap: !expr paste0(your_cap, ' (Column split 1 of 2, Row split 1 of 3)') + +table_list_split[[1]] |> + gt::tab_options(table.width = pct(100), table.layout = 'auto') |> + gt::cols_width(everything() ~ pct(20)) |> + asar::gt_split(row_every_n = 28) |> + gt::grp_pull(1) +``` + +::: +```` + +The next chunk would be identical except for a different label, caption, and would have `gt::grp_pull(2)` instead of `gt::grp_pull(1)`, for instance. When adding the second split table, add `table_list_split[[2]]` instead of `table_list_split[[1]]`, then change the label, caption, and `gt::grp_pull()` as needed. + +##### Final step: page break + +If you are adding multiple tables, insert a page break between them: + +```{verbatim} +{{< pagebreak >}} +``` + +#### Figures + +The workflow for figures is very similar to the workflow for regular tables. + +In your figures doc, add the following chunk to display the figure in your .qmd when it's rendered: + +````{verbatim} +```{r} +#| label: 'fig-custom1' # choose a label +#| echo: false +#| warning: false +#| fig-cap: !expr This is your figure caption. +#| fig-alt: !expr This is your figure alternative text. +# Import your data +your_df <- data.frame( + "x" = c(1, 2, 3), + "y" = c(4, 5, 6) +) + +# Make your figure +your_figure <- ggplot2::ggplot( + your_df, + aes( + x = x, + y = y + ) +) + + ggplot2::geom_point() + +# Show your figure +your_figure +``` +```` + +If you are adding another figure, add a page break first: + +```{verbatim} +{{< pagebreak >}} +``` diff --git a/vignettes/snippets/add-plots_img.Rmd b/vignettes/snippets/add-plots_img.Rmd new file mode 100644 index 00000000..149019af --- /dev/null +++ b/vignettes/snippets/add-plots_img.Rmd @@ -0,0 +1,83 @@ +### Add custom tables and figures {#sec-add-plots_img} + +In your 'report' folder, open your figures and tables docs (probably named something like '08_tables.qmd' and '09_figures.qmd'). Add the following code there. + + +**IMPORTANT**: The label in your captions/alt text csv must match the label in your plot's chunk options, **MINUS the "fig-" or "tab-"**. For example, the label "your_image_label_name" in the csv would match up properly with the "tbl-your_image_label_name" label in this code: + +``` rmd +![Your caption here](your_image.png){width=4in #fig-your_image_label_name} +``` + +The same rule applies for tables: "custom_table2" in the csv would match up with "tbl-custom_table2" in the markdown's label. + +#### Identify page orientation + +If you're using this workflow, your table/figure should be at most 8" wide or can be shrunken to 8" wide and still be legible. Find the width of your image file. Would you prefer to show it on a page with a portrait orientation (can fit 5" width) or landscape orientation (can fit 8" width)? + +Identify the preferred width of your image. Keep it in mind for when you add your image in the next section. + +#### Add image + +Next, add your image in this format ([see this Quarto documentation for more information](https://quarto.org/docs/authoring/figures.html)): + +``` markdown +![Your caption here](your_image.png){width=___in #fig-your_image_label_name} +``` +> **NOTE**: Remember that alternative text placed in this markdown format will not be put into your final report file; it must be in the captions_alt_text.csv file. However, *you must put the caption here*. + +> **NOTE**: It can be a headache to specify the correct image path. We recommend placing your files in either of these places: + +1. Your report folder (path = the image name, like *image.png*) +2. A folder within your report folder (path = the relative filepath, like *images/image.png* if there's an images folder within report) + +Here are some examples, using the following example folder structure setup: + +``` markdown +stock_assessments_2025/ +├── captions_alt_text.csv +├── report/ +│ ├── 01_executive_summary.qmd +│ ├── 02_introduction.qmd +│ ├── my_custom_figure.png +│ ├── images/ +│ │ ├── my_custom_table.png +``` + +``` markdown +# Example 1 +![Here is my caption to my example figure.](my_custom_figure.png){width=3in #fig-custom_figure1} +``` + +``` markdown +# Example 2 +![Here is my caption to my example table.](images/my_custom_table.png){width=5in #tab-custom_table1} +``` + +#### Add landscape braces (optional) + +If you'd like to place your image on a landscape-oriented page, you'll add [landscape braces](https://quarto.org/docs/authoring/article-layout.html#landscape-mode) before and after your table/figure to ensure it will be displayed properly, like this: + +```{verbatim} +::: {.landscape} +``` + +``` rmd +![Your caption here](your_image.png){width=___in #fig-your_image_label_name} +``` + +Then, add three colons to close the braces: + +```{verbatim} +::: +``` + +> **NOTE**: Landscape braces only work in [Quarto v1.6+](https://quarto.org/docs/blog/posts/2024-11-25-1.6-release/). Please read [this Discussion](https://github.com/nmfs-ost/asar/discussions/186) to learn how to check your Quarto version and update it if necessary. + +#### Page break + +If you are including more than one custom table or figure in a file, we suggest adding a page break to separate the tables/figures: + +```{verbatim} +{{< pagebreak >}} +``` diff --git a/vignettes/snippets/add-plots_rda.Rmd b/vignettes/snippets/add-plots_rda.Rmd new file mode 100644 index 00000000..a79bf8ad --- /dev/null +++ b/vignettes/snippets/add-plots_rda.Rmd @@ -0,0 +1,249 @@ +### Add custom tables and figures {#sec-add-plots_rda} + +In your 'report' folder, open your figures and tables docs (probably named something like '08_tables.qmd' and '09_figures.qmd'). Add the following code there. + + +**IMPORTANT**: The label in your captions/alt text csv must match the label in your plot's chunk options, **MINUS the "fig-" or "tab-"**. For example, the label "custom_table3" in the csv would match up properly with the "tbl-custom_table3" label in a code chunk. +The same rule applies for figures: "custom_figure1" in the csv would match up with "fig-custom_figure1" in the chunk options' label. + +#### Tables + +In your tables doc, add your first R chunk (shown below). This chunk is used to establish your `tables_dir` folder and load the library needed to plot your tables (`gt`). + +Click the following links to learn more about [cross-references](https://quarto.org/docs/computations/execution-options.html) (label) and [chunk options](https://quarto.org/docs/computations/execution-options.html) (echo, warning, etc.). + +````{verbatim} +```{r} +#| label: 'set-rda-dir-tbls-custom' +#| echo: false +#| warning: false +#| include: false +library(gt) +tables_dir <- "C:/path/to/your/tables" # set the path to your tables_dir +``` +```` + +Now, follow the instructions in the appropriate section depending on your table classification: **regular**, **wide**, **long**, **extra-wide**, or **extra-wide and long**. + +> **NOTE**: Landscape braces, used for wide and extra-wide tables, only work in [Quarto v1.6+](https://quarto.org/docs/blog/posts/2024-11-25-1.6-release/). Please read [this Discussion](https://github.com/nmfs-ost/asar/discussions/186) to learn how to check your Quarto version and update it if necessary. + +##### Regular table (`reg_reg`) + +Add the following chunk to import your table's rda and save objects containing the table and caption: + +````{verbatim} +```{r} +#| label: 'tbl-setup-custom1' # choose a label +#| echo: false +#| warning: false +#| include: false +# load your rda and save with a table-specific name, then delete "rda" +load(file.path(tables_dir, "example_table.rda")) +example_table_rda <- rda +rm(rda) + +# save table, caption as separate objects +example_table <- example_table_rda$table +example_cap <- example_table_rda$caption +``` +```` + +Then, add this chunk to display the table: + +````{verbatim} +```{r} +#| label: 'tbl-custom1' +#| echo: false +#| warning: false +#| eval: true +#| tbl-cap: !expr example_cap + +example_table +``` +```` + +##### Wide table (`wide_reg`) + +Import your rda using the same "Regular table" setup chunk above. Then, add [landscape braces](https://quarto.org/docs/authoring/article-layout.html#landscape-mode) and the display chunk: + +```{verbatim} +::: {.landscape} +``` + +````{verbatim} +```{r} +#| label: 'tbl-custom-wide1' # choose a label +#| echo: false +#| warning: false +#| tbl-cap: !expr example_cap + +# the tab_options() and cols_width() lines format the table to fit the landscape page +example_table |> + gt::tab_options(table.width = pct(100), table.layout = 'auto') |> + gt::cols_width(everything() ~ pct(20)) +``` +```` + +```{verbatim} +::: +``` + +##### Long table (`reg_long` or `wide_long`) + +Import your rda using the "Regular table" setup chunk. Long tables are split by row using `gt_split()`. You will need one chunk per page (e.g., if you have 2 pages, repeat the display chunk twice). + +> **NOTE**: For `wide_long` tables, wrap these chunks in `::: {.landscape}` braces. + +````{verbatim} +```{r} +#| label: 'tbl-custom-long1' # choose a label +#| echo: false +#| warning: false +#| tbl-cap: !expr paste0(example_cap, ' (1 of 2)') + +example_table |> + gt::tab_options(table.width = pct(100), table.layout = 'auto') |> + gt::cols_width(everything() ~ pct(20)) |> + asar::gt_split(row_every_n = 38) |> # Use 28 if wide_long + gt::grp_pull(1) # Use 2 for the second chunk, etc. +``` +```` + +##### Extra-wide table (`ewide_reg`) + +For extra-wide tables, load the split rda. This file contains a list of tables and their associated caption specifiers. + +````{verbatim} +```{r} +#| label: 'tbl-setup-ewide1' # choose a label +#| echo: false +#| warning: false +#| include: false +# Load the split rda +load(file.path(tables_dir, "example_tab_table_split.rda")) + +# Save the list and the caption specifiers +example_table_split <- table_list +example_cap_split <- names(example_table_split) +rm(table_list) +``` +```` + +Wrap each split table in landscape braces. Repeat the chunk below for each table in your `table_list`: + +```{verbatim} +::: {.landscape} +``` + +Then, add a chunk for each split table. Note how the caption is constructed using the specifiers: + +````{verbatim} +```{r} +#| label: 'tbl-custom-ewide1-part1' +#| echo: false +#| warning: false +#| tbl-cap: !expr paste0(example_cap_split, ' (1 of 2)') + +example_table_split[[1]] |> + gt::tab_options(table.width = pct(100), table.layout = 'auto') |> + gt::cols_width(everything() ~ pct(20)) +``` +```` + +```{verbatim} +::: +``` + +Duplicate the "tbl-custom-ewide1-part1" chunk above, changing the label, caption, and item pulled from the example_table_split object (e.g., `example_table_split[[2]]`) to add the rest of the split tables. + +##### Extra-wide, long table (`ewide_long`) + +For tables that are both extra-wide and long, you will use the same split rda import as above, but you will also apply the row-splitting logic to each chunk: + +```{verbatim} +::: {.landscape} +``` + +````{verbatim} +```{r} +#| label: 'tbl-ewide-long-c1-r1' +#| echo: false +#| tbl-cap: !expr paste0(example_cap_split, ' (1 of 2 tables split by column, 1 of 3 tables split by row)') + +example_table_split[[1]] |> + gt::tab_options(table.width = pct(100), table.layout = 'auto') |> + gt::cols_width(everything() ~ pct(20)) |> + asar::gt_split(row_every_n = 28) |> + gt::grp_pull(1) +``` +```` + +```{verbatim} +::: +``` + +Duplicate the "tbl-ewide-long-c1-r1" chunk above, changing the label, caption, item pulled from the example_table_split object (e.g., `example_table_split[[2]]`), *and* the portion of the table split by row (e.g., `grp_pull(2)`) to add the rest of the split tables. + +##### Final step: page break + +If you are adding multiple tables, regardless of size, add a page break between them to ensure they render on separate pages: + +```{verbatim} +{{< pagebreak >}} +``` + +#### Figures + +The workflow for figures is very similar to the workflow for regular tables. + +In your figures doc, add your first R chunk (shown below). This chunk is used to establish your figures_dir folder. + +Click the following links to learn more about [cross-references](https://quarto.org/docs/computations/execution-options.html) (label) and [chunk options](https://quarto.org/docs/computations/execution-options.html) (echo, warning, etc.). + +````{verbatim} +```{r} +#| label: 'set-rda-dir-figs-custom' # you can set this label as you wish, as long as it's not repeated in any other R chunk in, for instance, the 08_tables.qmd or 09_figures.qmd files. Labels are used for cross-referencing in your report text. +#| echo: false +#| warning: false +figures_dir <- "C:/path/to/your/figures" # set the path to your figures_dir +``` +```` + +Add the following chunk to your script to import your figure's rda and save objects containing the figure, caption, and alternative text: + +````{verbatim} +```{r} +#| label: 'fig-setup-custom1' # choose a label +#| echo: false +#| warning: false +#| include: false +# load your rda and save with a figure-specific name, then delete "rda" +load(file.path(figures_dir, "example_figure.rda")) +example_figure_rda <- rda +rm(rda) + +# save figure, caption, and alternative text as separate objects +example_plot <- example_figure_rda$figure +example_cap <- example_figure_rda$caption +example_alt_text <- example_figure_rda$alt_text +``` +```` + +Then, add this chunk to display the figure in your .qmd when it's rendered: + +````{verbatim} +```{r} +#| label: 'fig-custom1' # choose a label +#| echo: false +#| warning: false +#| fig-cap: !expr example_cap +#| fig-alt: !expr example_alt_text +example_plot +``` +```` + +If you are adding another figure, add a page break first: + +```{verbatim} +{{< pagebreak >}} +``` diff --git a/vignettes/snippets/code-custom-figs-tables.Rmd b/vignettes/snippets/code-custom-figs-tables.Rmd new file mode 100644 index 00000000..2211b75c --- /dev/null +++ b/vignettes/snippets/code-custom-figs-tables.Rmd @@ -0,0 +1,25 @@ +### Code your custom tables and figures {#sec-code-custom-figs-tables} + +First, write the code to produce (but not export; that's a future step!) your custom tables and figures. Save each table and figure as an object (e.g., in the examples below, `your_table` and `your_figure`). Save the script somewhere safe. + +```{r eval=F} +# Example dataframe +your_df <- data.frame( + "x" = c(1, 2, 3), + "y" = c(4, 5, 6) +) + +# Example table +your_table <- gt::gt(your_df) + +# Example figure +your_figure <- ggplot2::ggplot( + your_df, + aes( + x = x, + y = y + ) +) + + ggplot2::geom_point() +``` + diff --git a/vignettes/snippets/export-custom-figs-tables.Rmd b/vignettes/snippets/export-custom-figs-tables.Rmd new file mode 100644 index 00000000..ed41b07c --- /dev/null +++ b/vignettes/snippets/export-custom-figs-tables.Rmd @@ -0,0 +1,112 @@ +### Export your custom tables and figures {#sec-export-custom-figs-tables} + +Next, export your tables and figures to rda files. This code was adapted from functions like `stockplotr::plot_biomass`. + +#### Import pre-written captions and alternative text + +Import your csv containing your captions and alternative text and save it as an object. Then, save the captions and alternative text as separate objects. For example: + +```{r eval=F} +# Import captions and alternative text +my_text <- read.csv(file = "captions_alt_text.csv") + +# Extract table caption +my_table_cap <- my_text |> + dplyr::filter( + label == "example_table", + type == "table" + ) |> + dplyr::select(caption) |> + as.character() + +# Extract figure caption +my_figure_cap <- my_text |> + dplyr::filter( + label == "example_fig", + type == "figure" + ) |> + dplyr::select(caption) |> + as.character() + +# Extract figure alternative text +my_figure_alt_text <- my_text |> + dplyr::filter( + label == "example_fig", + type == "figure" + ) |> + dplyr::select(alt_text) |> + as.character() +``` + +> **NOTE**: Your label must match the label associated with your table or figure in your csv containing the captions and alternative text. If it does not match, the label will not be extracted properly and added to your rdas. + +#### Make rdas + +Your rdas will contain your table or figure, caption, and alternative text (if it's a figure). + +##### Tables + +```{r eval=F} +rda <- list( + "table" = your_table, # your table object + "caption" = my_table_cap # your table caption +) +``` + +##### Figures + +```{r eval=F} +rda <- list( + "figure" = your_figure, # your figure object + "caption" = my_figure_cap, # your figure caption + "alt_text" = my_figure_alt_text # your figure alternative text +) +``` + +#### Make 'figures' and 'tables' folders (if needed) + +Do you already have 'figures' and 'tables' folders? *Hint: both should be in your working directory.* If yes: Great! You can skip this step. If not, simply enter the code below to make the folders. + +```{r eval=FALSE} +dir.create(fs::path(getwd(), "figures")) +dir.create(fs::path(getwd(), "tables")) +``` + +#### Export your rdas + +##### Tables + +This will produce an rda called "example_table.rda" and save it in your 'tables' folder. + +**IMPORTANT**: Your table must have "_table" before the .rda file extension. For example, "custom_table1.rda" wouldn't work, but "custom1_table.rda" would work. + +```{r eval=FALSE} +save(rda, + file = fs::path( + getwd(), # this is your tables directory + "tables", + paste0( + "example_table.rda" # your table's label + ) + ) +) +``` + +##### Figures + +This will produce an rda called "example_figure.rda" and save it in your 'figures' folder. + +**IMPORTANT**: Your figure must have "_figure" before the .rda file extension. For example, "custom_figure1.rda" wouldn't work, but "custom1_figure.rda" would work. + +```{r eval=FALSE} +save(rda, + file = fs::path( + getwd(), # this is your figures directory + "figures", + paste0( + "example_figure.rda" # your figure's label + ) + ) +) +``` + diff --git a/vignettes/snippets/id_width.Rmd b/vignettes/snippets/id_width.Rmd new file mode 100644 index 00000000..bdfd41fa --- /dev/null +++ b/vignettes/snippets/id_width.Rmd @@ -0,0 +1,130 @@ +### Identify table width, length, orientation, and if splitting is necessary {#sec-id_width} + +*Skip this section if you are not including custom tables.* + +Your next step is to get a sense of your table dimensions. You'll ask: + +- Will each fit neatly into a portrait orientation, or should the page be rotated 90 degrees into landscape view? +- Even in landscape view, is the table too wide to be shown properly, and must be split into smaller tables by column? +- Is the table too long for one page, and must be split into smaller tables by row? + +This section contains the steps to answer these questions. + +> **NOTE**: This workflow is reflected in the create_tables_doc.R file and its associated functions (such as `render_lg_table()`, `ID_tbl_length_class()`, `ID_tbl_width_class()`, and `export_split_tbls()`). + +Run this code: + +```{r eval=F} +my_plot_name <- "example_table.rda" # replace this with the filename of your table rda +tables_dir <- getwd() # replace this with the location of your tables folder + +# Identify table width class +tbl_orient <- ID_tbl_width_class( + plot_name = gsub("_table.rda", "", my_plot_name), + tables_dir = tables_dir, + portrait_pg_width = 5 # 5 inches = the threshold for maximum table width before it needs to be resized, rotated, and/or split +) + +# Identify table length class +tbl_length <- ID_tbl_length_class( + plot_name = gsub("_table.rda", "", my_plot_name), + tables_dir = tables_dir + ) + +table_specs <- list(tbl_orient, tbl_length) + +# Identify table dimension class (length x width) +tbl_class <- dplyr::case_when( + table_specs[[1]] == "regular" & table_specs[[2]] == "regular" ~ "reg_reg", + table_specs[[1]] == "regular" & table_specs[[2]] == "long" ~ "reg_long", + table_specs[[1]] == "wide" & table_specs[[2]] == "regular" ~ "wide_reg", + table_specs[[1]] == "wide" & table_specs[[2]] == "long" ~ "wide_long", + table_specs[[1]] == "extra-wide" & table_specs[[2]] == "regular" ~ "ewide_reg", + table_specs[[1]] == "extra-wide" & table_specs[[2]] == "long" ~ "ewide_long", + TRUE ~ "unknown" + ) + +max_rows <- ifelse(tbl_orient == "regular", 38, 28) + +print(paste0("Your table dimension is ", tbl_class, ". The maximum number of table rows per page is ", max_rows, ".")) + +tables_path <- fs::path( + tables_dir, + "tables", + my_plot_name + ) + +load(tables_path) + +# Get table length in rows +split_table_rows <- length(rda[[1]]$`_data`[[1]]) +split_tables_rowwise <- ceiling(split_table_rows / max_rows) + +if (tbl_length == "long") { + print(paste0("Your table must be split row-wise. Each table can have, at most, ", max_rows, "rows.")) +} +if (tbl_orient == "extra-wide") { + print(paste0("Your table must be split column-wise. Proceed to the section 'Table splitting' (regarding extra-wide tables) to identify the number of smaller tables your original table must be split into.")) +} +``` + +You should see one of six outputs: reg_reg, reg_long, wide_reg, wide_long, ewide_reg, or ewide_long. + +| | | | | | | | +|-----------|:---------:|:---------:|:---------:|-----------|-----------|-----------| +| **Classification** | reg_reg | reg_long | wide_reg | wide_long | ewide_reg | ewide_long | +| **Dimensions** | Regular width & length | Regular width, long | Wide, regular length | Wide, long | Extra-wide, regular length | Extra-wide, long | +| **Table width** | \< 5" wide | \< 5" wide | at least 5" and up to 12" wide | at least 5" and up to 12" wide | \>12" wide | \>12" wide | +| **Table length**[^id_width-1] | \<= 38 rows | \> 38 rows | \<= 28 rows | \> 28 rows | \<= 28 rows | \> 28 rows | + +: Table width and length classification system coded in the `create_tables_doc` function. + +[^id_width-1]: The maximum number of rows drops from 38 (for regular-width tables) to 28 (for wide or extra-wide tables) because the latter two tables are rotated on a landscape page, which offers less space for table rows. + +**Regular-length tables** + +*If your output is reg_reg*, you can display your table in a .qmd chunk without any additional steps. Jump to section [Add custom tables and figures](#sec-add-plots) and proceed. + +*If your output is wide_reg*, you will place your table's .qmd chunk in special braces that change the page orientation to landscape. Jump to section [Add custom tables and figures](#sec-add-plots) and proceed. + +*If your output is ewide_reg*, you will place your table's .qmd chunk in special braces that change the page orientation to landscape *and* split it into narrower tables, each of which are displayed on separate pages. Proceed to the section [Table splitting](#sec-table-splitting). + +**Long tables** + +*If your output is reg_long*, you will split your table into shorter tables, each of which are displayed on separate pages. Proceed to the section [Table splitting](#sec-table-splitting). + +*If your output is wide_long*, you will place your table's .qmd chunk in special braces that change the page orientation to landscape *and* split your table into shorter tables, each of which are displayed on separate pages. Proceed to the section [Table splitting](#sec-table-splitting). + +*If your output is ewide_long*, you will place your table's .qmd chunk in special braces that change the page orientation to landscape; split it into narrower tables, each of which are displayed on separate pages; *and* split your table into shorter tables, each of which are displayed on separate pages. Proceed to the section [Table splitting](#sec-table-splitting). + +#### Table splitting {#sec-table-splitting} + +##### Extra-wide tables + +Extra-wide tables will need to be split among multiple pages. Run this code to learn the number of tables into which your original table will be split (by column) *and* export the split tables (as a list) into a new rda: + +```{r eval=F} +my_plot_name <- "example_table.rda" # replace this with the filename of your table rda +tables_dir <- getwd() # replace this with the location of your tables folder +essential_cols <- 1:2 # replace this with the columns that will be retained between the split tables, formatted as a sequence (e.g., 1:2 for columns 1-2, or 1 for a single column) + +export_split_tbls( + tables_dir = tables_dir, + plot_name = my_plot_name, + essential_columns = essential_cols +) +``` + +If the number returned was, say, 5, then since each split table must be in its own chunk, you will need 5 chunks to show your split tables by column (if your table is *ewide-long*, then you must also split tables by row). You will also need an additional chunk to load in the data. Each table needs its own chunk, and therefore label, so that it can be cross-referenced in text. + +You can check out your split tables in the new rda saved in your tables_dir folder. It will have the same filename as your original rda except that it will contain "\_split" in the filename. For instance, split tables created from "example_table.rda" will be saved in "example_table_table_split.rda". + +##### Long tables + +Long tables will need to be split among multiple pages. Refer to the code chunk above to learn the number of tables into which your original table will be split by row. + +If the number returned was, say, 3, then since each split table must be in its own chunk, you will need 3 chunks to show your split tables by row. You will also need an additional chunk to load in the data. Each table needs its own chunk, and therefore label, so that it can be cross-referenced in text. + +##### Extra-wide, long tables + +Extra-wide, long tables will need to be split by column *and* row. Read both "Extra-wide tables" and "Long tables" sections above, then proceed to the next section for guidance. diff --git a/vignettes/snippets/save-caps-alttext.Rmd b/vignettes/snippets/save-caps-alttext.Rmd new file mode 100644 index 00000000..f479b9bf --- /dev/null +++ b/vignettes/snippets/save-caps-alttext.Rmd @@ -0,0 +1,21 @@ +#### Saving text + +Do you have an existing captions_alt_text.csv file? If you've already generated a figure or table rda, this file should exist, most likely in your working directory. If you don't have one, run a `stockplotr` plotting function (e.g., `plot_biomass(make_rda = TRUE)`, `table_bnc(make_rda = TRUE)`) to generate the file. + +Open captions_alt_text.csv file, then add your text. The file is set up like this: + +- Column 1 ("label") is a shorthand label for your figure or table. Labels should be somewhat short and exclude spaces. Examples include "kobe", "relative.biomass", and "fishing.mortality". +- Column 2 ("type") contains "figure" or "table". +- Column 3 ("caption") contains your caption. +- Column 4 ("alt_text") contains alternative text for figures. For tables, this column will be blank. + ++-------------+------------+-----------------------------+--------------------------------------+ +| label | type | caption | alt_text | ++=============+============+=============================+======================================+ +| example_fig | figure | Example caption for figure. | Example alternative text for figure. | ++-------------+------------+-----------------------------+--------------------------------------+ +| example_tab | table | Example caption for table. | | ++-------------+------------+-----------------------------+--------------------------------------+ + +: Format for csv containing table and figure captions and alternative text. + diff --git a/vignettes/snippets/write-caps-alttext.Rmd b/vignettes/snippets/write-caps-alttext.Rmd new file mode 100644 index 00000000..2a234d06 --- /dev/null +++ b/vignettes/snippets/write-caps-alttext.Rmd @@ -0,0 +1,9 @@ +### Write captions and alternative text {#sec-write-caps-alttext} + +Once you know what your tables and figures look like, write your own captions and alternative text. Custom tables will require captions only. + +#### Writing text + +Check out the `stockplotr` ['captions_alt_text_template.csv' file](https://github.com/nmfs-ost/stockplotr/blob/master/inst/resources/captions_alt_text_template.csv), which contains the templates for each table or figure's caption/alternative text, to get a sense of how each description is structured. Then, refer to [the accessibility vignette's guide](https://nmfs-ost.github.io/asar/articles/accessibility_guide.html) to learn how to write clear and comprehensive alternative text. + +We recommend adding in key quantities, like maximum and minimum values, to ensure your captions and alternative text clearly describe your plots. For example, if you're showing how biomass changed over time, we recommend providing the maximum and minimum values of biomass and years shown, instead of simply stating that a figure shows biomass changing over time. Check out the ["How captions and alternative text are generated" vignette](https://nmfs-ost.github.io/stockplotr/articles/how-caps-alttext-are-made.html) to see how we extract certain key quantities from the model results files. You are welcome to use and adapt that code to your own results to calculate key quantities, or calculate the quantities with your own code.