Skip to content

Commit

Permalink
Fix #538
Browse files Browse the repository at this point in the history
  • Loading branch information
davidhodge931 committed Nov 19, 2023
1 parent 6e5d562 commit 7d3f26e
Showing 1 changed file with 36 additions and 21 deletions.
57 changes: 36 additions & 21 deletions vignettes/articles/3_go_further-Rmd.Rmd
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Expand All @@ -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)
)
```

0 comments on commit 7d3f26e

Please sign in to comment.