0
votes

I have a list of matrices. Each matrix in the list is of size Nx2. N may differ from matrix to matrix. I know how to use plot() to generate a scatter plot for each individual matrix. I wonder if there's an easy way to put scatter plot of each matrix into the same plot, and assign proper color to each matrix automatically.

For example, following code would generate a list containing two matrices. The first matrix is 20x2, the second is 10x2.

test = list()
test[[1]] <- replicate(2, rnorm(10))
test[[2]] <- replicate(2, rnorm(20))

I can use plot(test[[1]]) or plot(test[[2]]) to generate scatter plot for each individual matrix. But what I would like to do is to put the two scatter plots into the same plot, in which each matrix has different color. Since I'm looking for a method that can be generalized to up to 10 matrices, ideally, the color assignment should be automatic.

2
You need to determine the range of the x and y data, define "proper", and say which plotting paradigm you choose.IRTFM
Please provide a minimal, reproducible data set and the code you have tried.Henrik
How are you planning to have 10 distinct colours in one scatterplot that are easily distinguishable? Maybe you should consider using multiple plots or some other method of displaying the data.thelatemail

2 Answers

1
votes

If matrices is your list of matrices, you can do this:

data<-do.call(rbind,matrices)
colors<-c(mapply(rep,1:length(matrices),sapply(matrices,nrow)),recursive=T)  
plot(data,col=colors)

You can also build up the plot one matrix at a time, but in this case you have to figure out the ranges ahead of time, which is a bit of a pain:

xrange<-range(sapply(matrices,function(x)x[,1]))
yrange<-range(sapply(matrices,function(x)x[,2]))
plot(0,xlim=xrange,ylim=yrange,type="n")
for(i in 1:length(matrices))
  points(matrices[[i]],col=i)
0
votes

If you don't mind converting your matrices to a data frame, then you may try this alternative using ggplot:

library(ggplot2)

test2 <- lapply(seq_along(test), function(x){
  data.frame(test[[x]], grp = as.factor(x))
  })

df <- do.call(rbind, test2)

ggplot(data = df, aes(x = X1, y = X2, col = grp)) + geom_point()