ggsignif package error stat_signif requires the following missing aesthetics: y

This is an invented example of my data:

x <- c("Control", "Case", "Case", "Case", "Control", "Control", "Control", "Case", "Case", "Case")
y <- c("Dead", "Dead", "Dead", "Alive", "Alive", "Dead", "Dead", "Dead", "Alive", "Dead")

I'm trying to represent this data in the form of a bar plot and then indicate a statistically significant difference in the proportion of alive and dead patients between the two experimental groups (cases and controls). I performed a Pearson's chi square test and the p-value is 4.674e-06.

This is my code for the plot:

library(ggsignif)

ggplot(data, aes(x = data$x,
             fill = data$y)) + 
geom_bar(aes(y = stat(count/sum(count))), position = position_dodge(0.9)) + 
theme(plot.title = element_text(hjust = 0.5)) +
ylim(c(0, 0.4)) +
labs(x = NULL, y = "Proportion", fill = NULL) +
scale_x_discrete(labels = c("Control", "Case")) +
geom_signif(comparisons = list(c("Control", "Case"), map_signif_level = TRUE))

But then I get:

Error: stat_signif requires the following missing aesthetics: y

Could anyone please tell me why this is happening and how can I solve it?

Thanks

Upvotes: 3

Views: 1591

Answers (1)

Konrad Rudolph
Konrad Rudolph

Reputation: 545963

As indicated by the error message, geom_signif requires a y aesthetic, and you didn’t specify any.

Either move y = stat(count/sum(count)) from geom_bar to your global aesthetics, or add it to geom_signif’s aesthetics.

Next, fix your aesthetics: instead of data$x and data$y, use x and y. Furthmore, you have an error in geom_signif: map_signif_level = TRUE needs to be outside the comparisons.

Finally, geom_signif doesn’t seem to be able to work with computed statistics in aesthetics. So you need to compute this statistic beforehand, e.g. via dplyr:

data %>%
    group_by(x) %>%
    count(y) %>%
    mutate(Freq = n / sum(n)) %>%
    ggplot() +
    aes(x, Freq, fill = y) +
    geom_col(position = position_dodge(0.9)) +
    geom_signif(
        comparisons = list(c("Control", "Case")),
        map_signif_level = TRUE
    )

Upvotes: 1

Related Questions