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

874 views Asked by At

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:

  • All values of 0 map to white squares.
  • All values of 1 map to red squares.
  • All values of 2 map to blue squares.

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

2

There are 2 answers

0
Henrik On BEST ANSWER

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
0
erocoar On

One thing I could think of is to specify the color for each cell.

cellcolors <- unlist(grid)
cellcolors <- ifelse(cellcolors == 0, "white", ifelse(cellcolors == 1, "red", "blue"))
color2D.matplot(grid, ylab="", xlab = "", axes=F, cellcolors = cellcolors)

enter image description here