简体   繁体   中英

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: 在此处输入图片说明

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.

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)

在此处输入图片说明

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])

在此处输入图片说明


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM