elliot
elliot

Reputation: 1954

ggplot and ggsignif error on grouping variable

I'm getting this error when trying to run a geom_sig within ggplot.

Warning: Ignoring unknown aesthetics: xmin, xmax, annotations, y_position
Error in FUN(X[[i]], ...) : object 'Gender' not found 

My goal is to place significant indicators around dodged points in a faceted plot. I've tried to follow as close to package readme as possible, but I can't get past this error.

This code reproduces it.

library(tidyverse)
library(ggsignif)

set.seed(123)
df <- tibble(
  Gender = c(rep('Female',15), rep('Male',15)), 
  key = paste(sample(LETTERS, 30, T), sample(1:30, 30, F), sep = '_'),
  Value_mean = rnorm(30, 3, 1), 
  n = rep(100,30),
  sd = rnorm(30, 1, .5),
  se = rnorm(30, .05, .05),
  lower.ci = Value_mean - se,
  higher.ci = Value_mean + se, 
  trun_cat = rep(LETTERS[1:5], 6)
)




significant_df <- tibble(
  trun_cat = c('A','C','E'),
  start = c('H_29', 'R_24','L_23'),
  end = start,
  label = c('*', '**', '*'),
  y = rep(4.5,3))



df %>% 
ggplot(aes(
  fct_reorder(key, Value_mean, .desc = T),
  Value_mean,
  group  = Gender,
  color = Gender,
  fill = Gender
)) +
  geom_errorbar(
    aes(ymin = Value_mean - se,
        ymax = Value_mean + se,),
    width = .1,
    position = position_dodge(0.5),
    alpha = .9,
    show.legend = F
  ) +
  geom_point(
    position = position_dodge(0.5),
    size = 4,
    show.legend = T,
    alpha = 1
  ) + 
geom_signif(
  data = significant_df,
  aes(
    xmin = start,
    xmax = end,
    annotations = label,
    y_position = y
  ),
  textsize = 3,
  vjust = -0.2,
  manual = TRUE
)+
scale_color_grey() +
  scale_fill_grey() +
  facet_grid(~ trun_cat, scales = 'free_x')

How can I get around this error?

Upvotes: 2

Views: 1589

Answers (1)

Julius Vainora
Julius Vainora

Reputation: 48241

The issue is that geom_signif inherits the aesthetics define before and then looks for Gender in significant_df, which it doesn't find.

I'm not sure if that gives you a desired result, but to make the plot work you can add inherit.aes = FALSE:

geom_signif(
    inherit.aes = FALSE,
    ...

enter image description here

Upvotes: 3

Related Questions