From 7d3f26e13c3ddd474101e926394a8f3f32f92ce0 Mon Sep 17 00:00:00 2001 From: davidhodge931 Date: Mon, 20 Nov 2023 09:43:47 +1300 Subject: [PATCH] Fix #538 --- vignettes/articles/3_go_further-Rmd.Rmd | 57 ++++++++++++++++--------- 1 file changed, 36 insertions(+), 21 deletions(-) diff --git a/vignettes/articles/3_go_further-Rmd.Rmd b/vignettes/articles/3_go_further-Rmd.Rmd index 711ae279e..197b9574c 100644 --- a/vignettes/articles/3_go_further-Rmd.Rmd +++ b/vignettes/articles/3_go_further-Rmd.Rmd @@ -284,35 +284,47 @@ p1 / p2 ### 8. Add auto-contrast text on polygons -Text labels can be coloured based on the lightness/darkness of underlying polygons using a trick documented by [@teunbrand](https://github.com/teunbrand/ggplot_tricks). It requires `geom_text` to include the `show.legend = FALSE` argument. +Text labels can be coloured based on the lightness/darkness of underlying polygons using code developed by [@teunbrand](https://github.com/teunbrand/ggplot_tricks). It requires `geom_text` to include the `show.legend = FALSE` argument. ```{r} -contrast <- function(colour) { - out <- rep("#121b24", length(colour)) #use "#bbccdd" for dark_mode - light <- farver::get_channel(colour, "l", space = "hcl") - out[light < 50] <- "#fcfdfe" #use "#1f2f3e" for dark_mode - out +contrast <- + function(pal, + pal_dark = "#121b24", + pal_light = "#fcfdfe") { + + out <- rep(pal_dark, length(pal)) + light <- farver::get_channel(pal, "l", space = "hcl") + out[light < 50] <- pal_light + out + } + +aes_contrast <- { + aes(colour = after_scale(contrast(fill))) } -penguins2 |> - group_by(sex, species) |> - summarise(across(flipper_length_mm, \(x) mean(x, na.rm = TRUE))) |> - ungroup() |> +palmerpenguins::penguins |> + count(species, sex) |> gg_col( - x = flipper_length_mm, - y = sex, + x = sex, + y = n, col = species, - position = "dodge", - width = 0.75) + + pal = c("#0095A8", "#112E51", "#FF7043"), + width = 0.75, + position = position_dodge2(preserve = "single"), + x_labels = \(x) str_to_sentence(x), + col_legend_place = "right", + ) + geom_text( aes( - x = flipper_length_mm - (max(flipper_length_mm) * 0.05), - label = round(flipper_length_mm, 0), - !!!aes(colour = after_scale(contrast((fill)))) + y = n - (max(n * 0.04)), + label = n, + !!!aes_contrast, + # !!!aes(colour = after_scale(contrast(fill))), ), - show.legend = FALSE, + position = position_dodge2(width = 0.75, preserve = "single"), size = 3.53, - position = position_dodge(width = 0.75)) + show.legend = FALSE, + ) ``` ```{r} @@ -334,8 +346,11 @@ mtcars |> col_title = "r") + geom_text( aes(label = round(r, 1), - !!!aes(colour = after_scale(contrast(fill)))), + !!!aes_contrast, + # !!!aes(colour = after_scale(contrast(fill))), + ), + size = 3.53, show.legend = FALSE, - size = 3.53) + ) ```