Scijens
Scijens

Reputation: 561

Object not found in "geom_signif" function

I want to add significance stars for mean difference comparisons to a plot. Without the lines for the stars, the plot works:

da<-data.frame(group=c("condition1_high","condition1_low","condition2_high","condition2_low"),numb=c(30,25,26,20))

da %>% separate(group, c("A", "B"), remove = F) %>% 
  ggplot(aes(x=A, y=numb, fill = B)) +
  geom_bar(position=position_dodge(), stat="identity") +
  scale_fill_manual(values=rep(c("grey20","grey80"), ceiling(length(da$group)/2))[1:length(da$group)]) +
  geom_text(aes(label=numb), 
            position = position_dodge(width = 0.9), vjust = -0.25) +
  geom_signif(stat="identity",
              data=data.frame(x=c(0.5,1.5), xend=c(1,2),
                              y=c(30, 30), annotation=c("**", "*","***","+")),
              aes(x=x,xend=xend, y=y, yend=y, annotation=annotation))

Plot without stars

Now I add a bit of code for the stars I found here on this platform:

da %>% separate(group, c("A", "B"), remove = F) %>% 
  ggplot(aes(x=A, y=numb, fill = B)) +
  geom_bar(position=position_dodge(), stat="identity") +
  scale_fill_manual(values=rep(c("grey20","grey80"), ceiling(length(da$group)/2))[1:length(da$group)]) +
  geom_text(aes(label=numb), 
            position = position_dodge(width = 0.9), vjust = -0.25) +
  geom_signif(stat="identity",
              data=data.frame(x=c(0.5,1.5), xend=c(1,2),
                              y=c(30, 30), annotation=c("**", "*")),
              aes(x=x,xend=xend, y=y, yend=y, annotation=annotation))

Now it says that object B is missing. What can I do?

Upvotes: 0

Views: 705

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 174393

You need to add inherit.aes = FALSE to the geom_signif call, otherwise it will try to find a column called B in the new data frame you defined. This is because you put an aes call inside your initial call to ggplot. When you do this, by default all subsequent geoms will inherit the aesthetics and data from this call. If you pass new data to a geom, it needs to include a value for all those aesthetics or override the aesthetics or you need to switch off inheritance with inherit.aes = FALSE

da %>% 
  separate(group, c("A", "B"), remove = FALSE) %>% 
  ggplot(aes(x = A, y = numb, fill = B)) +
  geom_bar(position=position_dodge(), stat = "identity") +
  scale_fill_manual(values = rep(c("grey20", "grey80"),    
                                 ceiling(length(da$group)/2))[1:length(da$group)]) +
  geom_text(aes(label=numb), 
            position = position_dodge(width = 0.9), vjust = -0.25) +
  geom_signif(stat="identity", inherit.aes = FALSE,
              data=data.frame(x = c(0.5, 1.5), xend=c(1, 2),
                              y = c(30, 30), annotation = c("**", "*")),
              aes(x = x, xend = xend, y = y, yend = y, annotation = annotation))

enter image description here

Upvotes: 1

Related Questions