how to add the point plot for the scatterplot using pairs function in r?

Viewed 199

I have a scatter plot for the 10 variables samples . I also get the variable mean and variable median. I just wondering how to add the point plot of the mean and median to the scatterplot which is Pairs in r. If you have any other method(ggplot2) or function can achieve the same goal I am also willing to accept that.

Thank you so much for your great help and kindness

a <- matrix(rnorm(5000, 10, 1) + rgamma(5000, 1, 2), 50, 10)
var_mean <- apply(a, 2, mean)
var_median <- apply(a, 2, median)
pairs(a)
2 Answers

One quick way is to rbind the median and mean to the matrix, and specify a different color (with col=) and shape (with pch= ):

da = rbind(a,var_mean,var_median)
pairs(da,col = c(rep("black",nrow(a)),"blue","red"),
       pch= c(rep(20,nrow(a)),3,3),
       cex = c(rep(0.5,nrow(a)),1,1)
      )

enter image description here

You can't see the median and mean distinctly above because they are quite near one another

Here's a ggplot2 hack.

eg <- expand.grid(seq_len(ncol(a)), seq_len(ncol(a)))
eg <- eg[eg$Var1 != eg$Var2,]
head(eg,n=10)
#    Var1 Var2
# 2     2    1
# 3     3    1
# 4     4    1
# 5     5    1
# 6     6    1
# 7     7    1
# 8     8    1
# 9     9    1
# 10   10    1
# 11    1    2

bigdat <- do.call(rbind, Map(function(i,j) data.frame(Var1 = i, Var2 = j, x = a[,i], y = a[,j]), eg$Var1, eg$Var2))
stats <- do.call(rbind, Map(function(i,j) {
  data.frame(Var1 = i, Var2 = j, stat = c("mean", "median"),
             x = c(mean(a[,i]), median(a[,i])), y = c(mean(a[,j]), median(a[,j])))
}, eg$Var1, eg$Var2))
head(bigdat)
#   Var1 Var2         x         y
# 1    2    1  9.827221 10.389540
# 2    2    1  8.591226 10.657814
# 3    2    1 10.312920 10.796249
# 4    2    1 10.170430 11.316514
# 5    2    1  9.817480 11.049943
# 6    2    1 10.484015  8.171756
head(stats)
#   Var1 Var2   stat        x        y
# 1    2    1   mean 10.18291 10.61175
# 2    2    1 median 10.15589 10.62005
# 3    3    1   mean 10.40709 10.61175
# 4    3    1 median 10.56787 10.62005
# 5    4    1   mean 10.74154 10.61175
# 6    4    1 median 10.67607 10.62005

And the plot:

library(ggplot2)
ggplot(bigdat, aes(x, y)) +
  facet_grid(Var1 ~ Var2) +
  geom_point(color = "gray80") +
  geom_point(data = stats, aes(color = stat), size = 2)

ggplot2 pairs plot

Related