joketri
joketri

Reputation: 23

How to add significance of Tukey's test to ggplot2 figure with multiple facet?

I generated a plot using a long format table, ggplot() and facet_wrap() functions in Rstudio. I want to add values of Tukey's tests applied to different levels of data and annotated with a system of stars (or letters) for significance.

Here is the example code :

# create a df for example
a <- paste0("Sample_", rep(1:100, 1))
b <- c(rep("Dubai", 30), rep("London", 35), rep("Bucarest", 35))
c <- c(rep("Sun", 16), rep("Rain", 16), rep("Cloud", 17), rep("Thunder", 16), rep("Star", 35))
d <- runif(n = 100, min = 0.5, max = 50)
e <- runif(n = 100, min = 0.5, max = 50)
f <- runif(n = 100, min = 0.1, max = 3)

df <- data.frame("Sample"= a, "Location"=b, "Obs"=c, "Measure1"=d, "Measure2"=e, "Measure3"=f)

# convert df to long format
long <- reshape2::melt(df, id.vars = c("Sample", "Location", "Obs"), measure.vars = c("Measure1", "Measure2", "Measure3"))

# make a plot
p <- ggplot(long,aes(Location,value, color=Obs)) +
  facet_wrap(~ variable, drop=T, scale="free")+
  geom_boxplot(outlier.colour = NA, alpha=0.8, position = position_dodge2(width=1, preserve="single"))+
  geom_point(size=1.2, aes(shape=Obs), position=position_dodge(width=0.7, preserve='total'))+
  scale_shape_manual("Obs", values = c(16,17,17,16,16),
                     labels = c("Sun", 
                                "Rain",
                                "Cloud",
                                "Thunder", 
                                "Star"))+
  scale_color_manual("Obs", 
                     values=c("#00BF7D", "#5B6BF7", "#00B0F6", "#A3A500", "#F8766D"),
                     labels = c("Sun", 
                                "Rain",
                                "Cloud",
                                "Thunder", 
                                "Star"))+
  labs(x="Location", y = "Measure")+
  theme(legend.text.align = 0)

p

I get this : enter image description here

And I would like this : enter image description here

I tried with geom_signif() and stat_compare_means() functions but without success. Any idea please ?

Thank you for your attention.

Upvotes: 0

Views: 957

Answers (0)

Related Questions