rplotplotrix

R - How to assign color for values with color2d.matplot


My question deals with the color2d.matplot function from the plotrix package. The function is documented here.

I have this output: enter image description here

Produced by this code:

library(plotrix)

# model parameters
spaces <- 400
agents<- 300
prop_black = 0.5
prop_white = 1 - prop_black
tolerance <- 0.6

# creating matrix of types
group<-c(rep(0,spaces-agents),rep(1,prop_black*agents),rep(2,prop_white*agents))
grid<-matrix(sample(group,400,replace=F), ncol=20)

# plotting
color2D.matplot(grid, ylab="", xlab = "", axes=F)
plot(runif(100,0,1),ylab="Happy",xlab="Time",col="white",ylim=c(0,1))

Notice that my grid contains values of 0,1,2 only. How do I make it so that:

I tried to figure it out by looking at these examples but didn't have much luck.


Solution

  • You may index a colour vector with the values in your matrix. A smaller example:

    color2D.matplot(m, cellcolors = c("white", "red", "blue")[m + 1])
    

    enter image description here


    Data:

    set.seed(7)
    m <- matrix(sample(0:2, 9, replace = TRUE), nrow = 3, ncol = 3)
    m
    #      [,1] [,2] [,3]
    # [1,]    2    0    1
    # [2,]    1    0    2
    # [3,]    0    2    0