Created
September 2, 2026 17:06
-
-
Save bastianolea/3c3051a1096f5f2c9f5a210d67b6ce91 to your computer and use it in GitHub Desktop.
Quarto figures with height calculated from data rows
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| --- | |
| title: "Plot height test" | |
| format: | |
| html: | |
| embed-resources: true | |
| --- | |
| With parametrized Quarto reports, certain figures are expected to grow or shrink in widht/height based on existing data. This Quarto report demonstrates how to automatically adjust figure height based on the number of rows present in data. A horizontal column plot (where Y values are groups and X values are a continuous variable, so that bars grow sideways) of fixed height would simply shrink all columns to make them fit in the default height, but in this example, the plot height itself will increase according to the number of rows, so that all plots will have roughly the same column widths. | |
| ```{r setup} | |
| library(ggplot2) | |
| rows <- 23 | |
| ``` | |
| Data will have `{r} rows` rows. | |
| ```{r data} | |
| data <- data.frame( | |
| group = letters[1:rows], | |
| values = sample(10:90, rows, replace = TRUE) | |
| ) | |
| ``` | |
| ```{r height} | |
| base <- 0.3 | |
| height <- base * nrow(data) | |
| ``` | |
| Based on `{r} nrow(data)` rows, with a base height of `{r} base` per row, plot height will be `{r} height`. | |
| ```{r plot} | |
| #| fig-height: !expr height | |
| #| fig-width: 5 | |
| data |> | |
| ggplot() + | |
| aes(values, group) + | |
| geom_col() + | |
| theme_classic() | |
| ``` | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment