2

Hoping someone can point me in the right direction... I want to identify different groups on a QQ plot using ggplot... which appears to be easily done in base/stats qqnorm .eg.

set.seed(1967)
test <- as.data.frame(cbind( x= rnorm(100,5,2),y=c(rep(1,30),rep(2,70))))

qqnorm(test$x,col=test$y)

enter image description here

but ggplot gives me this:

ggplot(test, aes(sample=x,col=as.factor(y))) + geom_qq()

enter image description here

How do i achieve the qqnorm plot with ggplot? I tried searching here... found similar, but no concise answer... surely I'm missing some trivial switch thing?

Z.Lin
  • 28,055
  • 6
  • 54
  • 94
mando_R
  • 63
  • 5
  • 1
    I just posted a new answer to the question @Tjebo linked above. Adding an explicit grouping variable (e.g. `aes(group = 1)`) should work for this case too. – Z.Lin Jun 23 '20 at 11:08

1 Answers1

3

The issue is that we can not color the points via the color aes as this splits the data into groups, i.e. we get a qq-plot for each group instead of for the whole sample.

To overcome this problem my approach colors the points via the color argument. This however requires some manual work. First. Set up the color vector according to the test$y. Second, to get the right colors in the plot we have to order the color vector by test$x. Hard work but at least it works. (; Try this:

library(ggplot2)

set.seed(1967)
test <- as.data.frame(cbind( x = rnorm(100,5,2),y=c(rep(1,30),rep(2,70))))

# Vector of colors
col <- ifelse(test$y == 1, scales::hue_pal()(2)[1], scales::hue_pal()(2)[2])
# Order by x
col <- col[order(test$x)]

ggplot(test) + 
  geom_qq(aes(sample=x), col=col)

PS: Thanks to @Tjebo for checking and pointing out that I don't need geom_point to get the right colors.

stefan
  • 90,330
  • 6
  • 25
  • 51
  • 1
    @Tjebo. Thanks. You are right. Not sure what I tried. (: Just edited my code accordingly. – stefan Jun 23 '20 at 08:37
  • this is just what i needed! I mashed it all together to into `ggplot(test) + geom_qq(aes(sample=x),col=ifelse(test$y == 1, "red", "black")[order(test$x)])` – mando_R Jun 23 '20 at 14:30