after_stat() conditional fill in geom_bar() not working as expected
Closed this issue · 2 comments
When using after_stat() with a conditional expression for fill aesthetic in geom_bar(),
all bars are filled with the same color regardless of the condition result.
This works correctly when precomputing the values outside of ggplot2.
Bars should have different colors based on the condition after_stat(prop > 0.3).
All bars have the same color.
r
library(ggplot2)
test_data <- data.frame(
category = factor(c("A", "B", "C", "D")),
count = c(10, 30, 40, 20)
)
problem that i met:
p <- ggplot(test_data) +
geom_bar(aes(x = category,
y = after_stat(prop),
fill = after_stat(prop > 0.3)),
group = 1)
print(p)
test_data_prop <- test_data %>%
dplyr::mutate(prop = count / sum(count),
highlight = prop > 0.3)
ggplot(test_data_prop, aes(x = category, y = prop, fill = highlight)) +
geom_col()
You should include group = 1 inside the aes(). Giving it outside the mapping argument only adds the group in the after_scale() phase.
Bars should have different colors based on the condition after_stat(prop > 0.3).
In the example you give: no. You'd then expect all 4 bars to have count = 1 and thus have prop = 0.25 and get coloured by prop > 0.3 == FALSE.
Closing this issue as I think this is all working as expected.