Skip to content

after_stat() conditional fill in geom_bar() not working as expected #6592

@yangxiqin2024-tech

Description

@yangxiqin2024-tech

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions