jame_path
jame_path

Reputation: 63

Using ggsignif with grouped bar graphs and facet_wrap not working

I am trying to use ggsignif for displaying significant stars in top of paired bar graphs using facet_wrap. However, I can´t manage to find a way of displaying one significant bar per facet. Here is what I mean:

    dat <- data.frame(Group = c("S1", "S1", "S2", "S2"),
                  Sub   = c("A", "B", "A", "B"),
                  Value = c(3,5,7,8))

    ggplot(dat, aes(Group, Value)) +
      geom_bar(aes(fill = Sub), stat="identity", position="dodge", width=.5) +
      geom_signif(y_position=c(5.3, 8.3), xmin=c(0.8, 1.8), xmax=c(1.2, 2.2),
              annotation=c("**", "NS"), tip_length=0) +
      scale_fill_manual(values = c("grey80", "grey20")) +
      facet_grid(~ Group, scales = "free")

output

Is there a way of making sure that each facet has its individual significance label?

Upvotes: 6

Views: 7619

Answers (2)

Kresten
Kresten

Reputation: 1888

Have you considered using ggpubr and stat_compare_means? https://rpkgs.datanovia.com/ggpubr/reference/stat_compare_means.html

Since your example only contains one observation pr. bar it does not work but if you include multiple observations you can get what you want.

rewrite the test data:

dat <- data.frame(A_S1 = sample(rnorm(20, 3, 1)),
              B_S1 = sample(rnorm(20, 5, 1)),
              A_S2 = sample(rnorm(20, 7, 1)),
              B_S2 = sample(rnorm(20, 8, 1))) %>% 
tidyr::gather("G", "value") %>% 
tidyr::separate("G", c("Sub", "Group"))

Plot the data using the ggpubr package

ggerrorplot(dat, x = "Sub", y = "value",
            facet.by = "Group",
            error.plot = "pointrange") +
stat_compare_means(aes(label = ..p.signif..),
                   method = "t.test", ref.group = "A")

enter image description here

Upvotes: 0

teunbrand
teunbrand

Reputation: 38023

The main problem seems to me is that the geom_signif layer doesn't know to what panel the variables go to, since it has no data argument provided.

I'm not that familiar with the package, but the documentation seems to suggest that manual = TRUE is recommended for plotting it in different facets. Doing that and making some adjustments for the errors that were thrown, I got the following to work:

ggplot(dat, aes(Group, Value)) +
  geom_bar(aes(fill = Sub), stat="identity", position="dodge", width=.5) +
  geom_signif(data = data.frame(Group = c("S1","S2")),
              aes(y_position=c(5.3, 8.3), xmin=c(0.8, 0.8), xmax=c(1.2, 1.2),
              annotations=c("**", "NS")), tip_length=0, manual = T) +
  scale_fill_manual(values = c("grey80", "grey20")) +
  facet_grid(~ Group, scales = "free")

enter image description here

The key seemed to be to provide a data argument from which the facetting code could deduce what bit goes in what panel.

Upvotes: 7

Related Questions