Search code examples
rlatticelevelplotcellular-automata

Cellular Automaton in R - disappearing states change color in levelplot


Good afternoon everyone!

Currently working on a cellular automaton in R (modelling of an epidemic applied to invasive species). Cells can be in 4 different states: 0, 1, 2, 3. So far I've made a plot (using levelplot) of the matrix, and watch it change for a fixed number of steps (according to a set rule and the number of each type of neighbours).

Code is as follows (the entire script is not shown):

matriu # matrix with cells in either state (0,1,2,3)
colors  <- colorRampPalette(c("green", "red", "white", "blue"))
graph   <- levelplot(matriu, col.regions = colors, cuts = 3)
print(graph)

As the automaton changes step by step, it is possible to lose 1 or 2 states. This means the matrix can transition from having states (0,1,2,3) to having states (0,1,2) or (1,2).

I've tried to embed a couple of images of the coloured matrix with 4 states vs. 3 states, but since it's first I'm posting a question here, appareantly they'll show up as image (hope it works!).

Levelplot with 4 states:

levelplot with 4 states

Levelplot with 3 states:

levelplot with 3 states

When the 4 states are present, state 2 is shown as white, but when only 3 states remain (second picture), state 2 is shown as blue.

My question is: how to prevent to colors from shifting, in the event that one or more states disappear?

I'm just starting to learn to code using R, so this page has been very useful lately. Thanks to all of you that keep this place alive!


Solution

  • Use the at argument for levelplot. For example:

    library(lattice)
    set.seed(123)
    matriu <- matrix(sample(0:3, 100, replace = TRUE), nc = 10)
    colors  <- colorRampPalette(c("green", "red", "white", "blue"))
    graph   <- levelplot(matriu, col.regions = colors, at = c(-.1, .5:2.5, 3.1))
    graph
    

    enter image description here

    matriu <- matrix(sample(1:2, 100, replace = TRUE), nc = 10)
    graph   <- levelplot(matriu, col.regions = colors, at = c(-.1, .5:2.5, 3.1))
    graph
    

    enter image description here

    P.s. Welcome to SO -- please try to provide a minimal working example (e.g. some fake data for matriu) with your question.