Home > OS >  Adding RGB channel to the 2D matrix [R]
Adding RGB channel to the 2D matrix [R]

Time:11-26

Here is an example matrix:

mymat <-matrix(runif(24*24), ncol=24) 

I can plot this matrix using ggplot2, so I can obtain color representation of values:

plot_mat <- function(mat){
  mat_df<- reshape2::melt(mat)
  plt <- mat_df %>% ggplot2::ggplot(aes(Var2, Var1))   geom_raster(aes(fill = value))  scale_fill_gradientn(colours = c('blue', 'green', 'yellow', 'red'))   theme_bw()
  return(plt)
}

plot_mat(mymat)

But I would like to add RGB channel to my data without converting them into an image. I would like to add another dimension to my mymat, so the dim(mymat) output would look 24, 24, 3. Unfortunately, I do not know, how to do so.

I would be grateful for your help.

CodePudding user response:

You can extract the colors used in your plot with ggplot_build(), they are stored as hex colors, convert it to RGB colors with col2rgb() and reshape it using array(). If the resulting array is not properly sorted you can fix it likely with transposing t() onto the final results or one of the outputs throughout the steps will be enough.

set.seed(123) # For reproducibility

mymat <-matrix(runif(24*24), ncol=24) 

plot_mat <- function(mat){
  mat_df<- reshape2::melt(mat)
  plt <- mat_df %>% ggplot2::ggplot(aes(Var2, Var1))   geom_raster(aes(fill = value))  scale_fill_gradientn(colours = c('blue', 'green', 'yellow', 'red'))   theme_bw()

  pg <- ggplot_build(plt) # Extract data from the plot
  RGBcolors <- col2rgb(pg$data[[1]]$fill, alpha = FALSE) # Transform the fill column to RGB 2D matrix

  RGB_array <- array(t(RGBcolors), c(24,24,3)); # create new array reshaping to 24x24x3
# t() to transpose RGBcolors matrix to fit new third dimension
  RGB_array <- DescTools::Rev(RGB_array, margin=1) # RGB_array  array is flipped
  return(RGB_array)
}
  • Related