QQ chart with ggplot2 :: stat_qq, colors, one group

I am looking for a more convenient way to get the QQ graph in ggplot2 , where the quantiles are computed for the dataset as a whole. but I can use mappings (color / shapes) for groups in the data.

 library(dplyr) library(ggplot2) library(broom) ## for augment() 

Make some data:

 set.seed(1001) N <- 1000 G <- 10 dd <- data_frame(x=runif(N), f=factor(sample(1:G,size=N,replace=TRUE)), y=rnorm(N)+2*x+as.numeric(f)) m1 <- lm(y~x,data=dd) dda <- cbind(augment(m1),f=dd$f) 

The main plot:

 ggplot(dda)+stat_qq(aes(sample=.resid)) 

enter image description here

If I try to add color, the groups will be separated to calculate quantiles (which I don't want):

 ggplot(dda)+stat_qq(aes(sample=y,colour=f)) 

enter image description here

If I use stat_qq(aes(sample=y,colour=f,group=1)) , ggplot ignores the color specification, and I return the first graph.

I need a plot where the points are located in the same way as in the first case, but colored as in the second case. I have a qqnorm based qqnorm that I can post, but I'm looking for something nicer ...

+5
source share
1 answer

You can calculate the quantiles yourself and then build using geom_point :

 dda = cbind(dda, setNames(qqnorm(dda$.resid, plot.it=FALSE), c("Theoretical", "Sample"))) ggplot(dda) + geom_point(aes(x=Theoretical, y=Sample, colour=f)) 

enter image description here

And, I think, I should have read until the end of your question. This is the manual solution you were addressing, isn't it? Although you can just pack it as a function:

 my_stat_qq = function(data, colour.var) { data=cbind(data, setNames(qqnorm(data$.resid, plot.it=FALSE), c("Theoretical", "Sample"))) ggplot(data) + geom_point(aes_string(x="Theoretical", y="Sample", colour=colour.var)) } my_stat_qq(dda, "f") 
+2
source

Source: https://habr.com/ru/post/1265196/


All Articles