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()