Home > Blockchain >  Add significance brackets to horizontal barplot
Add significance brackets to horizontal barplot

Time:06-15

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)

CodePudding user response:

enter image description here

  •  Tags:  
  • r
  • Related