2017-06-08 8 views
0

密度プロットにShapiroテストのp値(法線を確認する)を追加するにはどうすればよいですか? geom_text(aes(y = 1, label = p.value), data = shapiro.test, size = 1)を使用しようとしましたが、エラーが発生しました。 、彼らはあなたが期待するようgeom_textが動作するために同じ長さである必要はありres.data.plotとして密度プロットにshapiro test p-valueを追加する方法

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)) 

答えて

1

shapiro.testオブジェクト内のデータは同じ長さではありません。

両方のオブジェクトを結合することができるので、プロットは簡単になります。私はxとyの範囲becuaseのx = 1、Y = 1を使用するのではなく、各プロットの右コーナーにすべてのラベルをもたらすことができますどのように

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))) 
+0

素晴らしい、本当にありがとうございました – shad

+0

ただ一つの質問は、各プロットのために異なっています。 – shad

+0

ファセットに自由なスケールがあるので、xとyの相対位置を指定する必要があります。 [ggplot2のgeom_textの相対的な配置?](https://stackoverflow.com/questions/7611691/relative-positioning-of-geom-text-in-ggplot2)これを行う方法については、この質問を見てください。 –

関連する問題