Created
June 28, 2024 14:07
-
-
Save matt-dray/ff48017ba793ed1610787004c69c2acc to your computer and use it in GitHub Desktop.
{ggplot2} plot-height determined by facet row count: halve the height of the output if the second facet row is missing
This file contains 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
# Calculate how many plots will be produced | |
count_plots <- function(df, var) { | |
length(unique(df[[var]])) | |
} | |
# Plot faceted chart, save with height dependent on plot count | |
write_responsive_facets <- function( | |
df, | |
var = "species", | |
plot_count = count_plots(df, var), | |
facet_cols = 2, | |
write_dir | |
) { | |
p <- df |> | |
ggplot2::ggplot(ggplot2::aes(bill_length_mm, bill_depth_mm) ) + | |
ggplot2::geom_point() + | |
ggplot2::facet_wrap(~species, ncol = facet_cols) | |
# Save at half-height if only one facet row is used | |
if (plot_count > facet_cols) responsive_height <- 10 | |
if (plot_count <= facet_cols) responsive_height <- 5 | |
ggplot2::ggsave( | |
glue::glue("{write_dir}/test-{plot_count}-plots.png"), | |
width = 10, | |
height = responsive_height | |
) | |
} | |
# Data with three plots: 2 on top facet row, 1 below | |
peng_3_sp <- palmerpenguins::penguins |> | |
tidyr::drop_na(species, bill_length_mm, bill_depth_mm) | |
# Data with two plots: 2 on top facet row, zero below | |
peng_2_sp <- peng_3_sp |> dplyr::filter(species != "Gentoo") | |
write_responsive_facets(peng_3_sp) # 2x2 facets, height 10 | |
write_responsive_facets(peng_2_sp) # 1x2 facets, height 5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
With three plots:
With two plots: