Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add significance brackets to horizontal barplot

In my dataset, respondents in two different groups were invited to select or not select a series of variables. I can get this to work to add significance stars to a standard vertical barplot, but I would like to be able to rotate it and make it horizontal. Is that at all possible?

#dataframe
group1<-sample(c("A", "B"), 100, replace=T)
var1<-sample(c(0,1),100, replace=T, prob=c(0.3, 0.7))
var2<-sample(c(0,1),100, replace=T, prob=c(0.4, 0.6))
var3<-sample(c(0,1),100, replace=T, prob=c(0.8, 0.2))
df<-data.frame(group1, var1, var2, var3)
library(tidyverse)
library(broom)
#Pivot
df %>% 
  pivot_longer(-group1) %>% 
  group_by(group1, name, value) %>% 
  #summarize(n=n()) %>% 
#Nest by variable
  nest(-name) %>%
#For each variable run the chi-squared test of group on whether or not 
# it was selected 
  mutate(model=map(data, ~chisq.test(.$group1, .$value)), 
#Tidy the results
         tidied=map(model, tidy)) %>% 
#unnest and store in new object
  unnest(tidied)->x2_test
#Adjust p-values for multiple comparisons 
x2_test$p.value<-p.adjust(x2_test$p.value, method="bonferroni", n=3)
x2_test

library(ggsignif)
#draw the plot 
df %>% 
  pivot_longer(-group1) %>% 
  group_by(name, group1, value) %>% 
  summarize(n=n()) %>% 
  ggplot(., aes(x=name,y=n))+geom_col(position="dodge", aes(fill=group1))+
#Set the positions of some significance tests at about y=50 
 geom_signif(y_position=c(50,50,50), xmin=c(0.8, 1.8, 2.2),xmax=c(1.2,2.2, 3),
              annotation=c(x2_test$p.value), map_signif_level = T)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ggplot2 3.3.0 in 2020 introduced more robust switching between vertical and horizontal layouts. If you’re using a more recent version of ggplot2, you should be able to change the mapping at the outset:

... %>%
ggplot(., aes(y=name,x=n)) + ...

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading