0

How can I add the p value of the Shapiro test (checking normality) into the density plot? I tried to use geom_text(aes(y = 1, label = p.value), data = shapiro.test, size = 1) but I got the error.

 formula <- as.formula(paste0("cbind(", paste(names(mtcars)[-c(4,9)], collapse = ","), ") ~ hp*am"))
    fit <- aov(formula, data=mtcars)
    res.data.plot <-data.frame(melt(resid(fit)))
    res.data.test <-data.frame(resid(fit))
#plot       
        res.plot <- ggplot(res.data.plot, aes(x=value)) + 
                    geom_histogram(aes(y=..density..), binwidth=.5,colour="black", fill="white")+      
                    geom_density(alpha=.2, fill="#FF6666")+ facet_wrap( ~X2, scales="free")

# shapiro test
        kk<-Map(function(x)cbind(shapiro.test(x)$statistic,shapiro.test(x)$p.value),res.data.test)
        shapiro.test <-ldply(kk)
        names(shapiro.test)<-c("var","W","p.value")
        shapiro.test<- plyr::arrange(shapiro.test, var, desc(p.value))
Axeman
  • 32,068
  • 8
  • 81
  • 94
shad
  • 25
  • 5

1 Answers1

2

The data in the shapiro.test object is not the same length as res.data.plot, they need to be the same length for geom_text to work as you expect.

You can merge both objects, so plotting becomes straightforward.

res.data.plot.new <- merge(res.data.plot, shapiro.test, by.x = "Var2", by.y = "var")

ggplot(res.data.plot.new, aes(x=value)) + 
  geom_histogram(aes(y=..density..), binwidth=.5, colour="black", fill="white") +      
  geom_density(alpha=.2, fill="#FF6666") + 
  facet_wrap( ~Var2, scales="free") +
  geom_text(aes(x = 1, y = 1, label = round(p.value, 4)))
Juan Bosco
  • 1,420
  • 5
  • 19
  • 23
  • just one question, How can I bring all the label to the right corner of each plot instead of using x=1 y=1 becuase the x and y range is different for each plot. – shad Jun 09 '17 at 13:10
  • As you have free scales in your facets, you need to specify a relative position for x and y. Take a look at this question for a way to do this: [Relative positioning of geom_text in ggplot2?](https://stackoverflow.com/questions/7611691/relative-positioning-of-geom-text-in-ggplot2) – Juan Bosco Jun 09 '17 at 16:00