Skip to content

Instantly share code, notes, and snippets.

@yjunechoe
Created May 6, 2024 02:07
Show Gist options
  • Save yjunechoe/beb296e98f06f190acda83e29bdc90c4 to your computer and use it in GitHub Desktop.
Save yjunechoe/beb296e98f06f190acda83e29bdc90c4 to your computer and use it in GitHub Desktop.
highlight_color_by()
# The reprex
library(ggplot2)
data <- tibble::tribble(
~x, ~group, ~y, ~measure, ~base,
"FY18", "aaa", 0.5603448, 260, 464,
"FY15", "aaa", 0.5081269, 1313, 2584,
"FY19", "aaa", 0.5799373, 185, 319,
"FY16", "aaa", 0.5225225, 580, 1110,
"FY13", "aaa", 0.4779116, 595, 1245,
"FY17", "aaa", 0.5502471, 334, 607,
"FY14", "aaa", 0.5339007, 1882, 3525,
"FY20", "aaa", 0.4960998, 318, 641,
"FY21", "aaa", 0.4765840, 173, 363,
"FY21", "bbb", 0.5135802, 208, 405,
"FY20", "bbb", 0.5384615, 259, 481,
"FY17", "bbb", 0.4628099, 56, 121,
"FY18", "bbb", 0.5474453, 75, 137,
"FY15", "bbb", 0.4705882, 72, 153,
"FY19", "bbb", 0.6083916, 87, 143,
"FY14", "bbb", 0.5097087, 105, 206,
"FY16", "bbb", 0.5395683, 75, 139,
"FY13", "bbb", 0.5432099, 132, 243,
"FY14", "ccc", 0.5326591, 2528, 4746,
"FY21", "ccc", 0.4320038, 899, 2081,
"FY13", "ccc", 0.5420887, 3265, 6023,
"FY16", "ccc", 0.5075188, 810, 1596,
"FY15", "ccc", 0.5116469, 1252, 2447,
"FY18", "ccc", 0.4206349, 477, 1134,
"FY17", "ccc", 0.4564565, 456, 999,
"FY19", "ccc", 0.4651429, 407, 875,
"FY20", "ccc", 0.4759398, 633, 1330
)
highlight_color_by <- function(expr, hl_colour = "#018d47") {
aes(color = I(ifelse({{ expr }}, !!hl_colour, "#AA43FA")))
}
ggplot(data, aes(x, y)) +
geom_line(
aes(group = group, !!!highlight_color_by(group == "ccc"))
)
# Another example
set.seed(1)
data2 <- expand.grid(x = 1:10, group_A = gl(3, 1), group_B = gl(2, 1)) |>
transform(y = rnorm(60))
ggplot(data2, aes(x, y)) +
geom_line(
aes(group = interaction(group_A, group_B),
!!!highlight_color_by(group_B == 1))
)
# Not just line geom - works with any geom that takes understands group & color
ggplot(data2, aes(sample(x), y)) +
geom_path(aes(!!!highlight_color_by(group_B == 1 & group_A == 2))) +
facet_grid(group_A ~ group_B)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment