Reputation: 25
I'm trying to change the color of the text labels associated with specific data points in a bar chart using ggplot2.
Here is the original code - using mtcars as an example:
mtcars_gear_percentage_by_make <- mtcars %>%
tibble::rownames_to_column(var = "car") %>%
tidyr::separate(car, c("make", "model"), sep = "\\s") %>%
dplyr::filter(make == "Merc" | make == "Toyota") %>%
dplyr::group_by(make, gear) %>%
dplyr::summarize(n_model = n()) %>%
dplyr::mutate(percentage_gear = n_model / sum(n_model, na.rm = TRUE))
ggplot(mtcars_gear_percentage_by_make,
aes(x = make, y = percentage_gear, fill = gear, label = round(percentage_gear, 2))) +
geom_col() +
geom_label(position = position_stack(vjust = 0.5))
And here is the plot it generates:
Is there a way to change the color of the text labels in the dark blue part to white, while leaving the color of the text labels in the lighter blue part unchanged?
Thank you!
Upvotes: 1
Views: 1362
Reputation: 174268
A safer way to do this is to assign the colour aesthetic according to the fill group it will overlay:
ggplot(mtcars_gear_percentage_by_make,
aes(x = make, y = percentage_gear, fill = gear, label = round(percentage_gear, 2))) +
geom_col() +
geom_label(aes(colour = gear),
position = position_stack(vjust = 0.5)) +
scale_color_gradient(low = "white", high = "black", guide = guide_none())
Upvotes: 1