Search code examples
rmatrixvisualizationgrid-layout

Color squares of a grid according to labels


I have created a 100x100 grid using the following code:

nb=100
nb1=nb
nb2=nb
minlat=45.18306
maxlat=45.6325
binlat=seq(minlat-0.05, maxlat+0.05, length.out = nb1)
minlon=8.724444
maxlon=9.519722
binlon=seq(minlon-0.05, maxlon+0.05, length.out = nb2)

And my data is grouped like follows:

n = 100
coord = matrix(0, n, 2)
coord[,1]= runif(100, min=45.18306, max=45.6325)
coord[,2]= runif(100, min=8.724444, max=9.519722)

lab=matrix(0, n, 1)
m=1
for(i in 1:nb1){
  for(j in 1:nb2){
    lab[coord[,1]>binlat[i] & coord[,1]<=binlat[i+1] & coord[,2]>binlon[j] & coord[,2]<=binlon[j+1]]=m
    m=m+1
  }
}

Assuming I have a matrix like the following:

a <- c(1000,2536,3045,6654)
b <- c(1,1,2,3)
matrix <- cbind(a,b)

where a is the vector identifying the grid square ID and b is the vector of the group to which the square belongs.

Is it possible to visualize the grid with the squares in a colored according to the group they belong to? All the squares not included in a must be non-colored/white.


Solution

  • You can use expand.grid to get a data frame of all the unique x and y values making up a grid.

    df <- expand.grid(x = binlon, y = binlat)
    

    This will give you all the x values at each y value in order:

    head(df)
    #>          x        y
    #> 1 8.674444 45.13306
    #> 2 8.683487 45.13306
    #> 3 8.692530 45.13306 
    #> 4 8.701574 45.13306
    #> 5 8.710617 45.13306
    #> 6 8.719660 45.13306
    

    ...and so on for 10,000 rows.

    If your a column represents the matrix position of a cell with this ordering, then you can label the correct cell with a group by doing:

    df$group <- NA_real_
    df$group[matrix[,'a']] <- matrix[,'b']
    df$group <- factor(df$group)
    

    (if this is transposed from what you intended, simply reverse the order of the arguments in expand.grid)

    Plotting the result is probably easiest using ggplot

    library(ggplot2)
    
    ggplot(df, aes(x, y, fill = group)) + 
      geom_tile(colour = 'gray90') +
      scale_fill_brewer(palette = 'Set1', na.value = 'white')
    

    enter image description here