Search code examples
rheatmaprasterr-grid

Creating a 2D-grid or raster in R comparing all respondents with all variables


reproducible example for my data:

df_1 <- data.frame(cbind("Thriving" = c(2.33, 4.21, 6.37, 5.28, 4.87, 3.92, 4.16, 5.53), "Satisfaction" = c(3.45, 4.53, 6.01, 3.87, 2.92, 4.50, 5.89, 4.72), "Wellbeing" = c(2.82, 3.45, 5.23, 3.93, 6.18, 4.22, 3.68, 4.74), "id" = c(1:8)))

As you can see, it includes three variables of psychological measures and one identifier with an id for each respondent.

Now, my aim is to create a 2D-grid with which I can have a nice overview of all the values for all respondents concerning each of the variables. So on the x-axis I would have the id of all the respondents and on the y-axis all variables, whereas the colour of the particular field depends on the value - 1 to 3 in red, 3 to 5 in yellow and 5 to 7 in green The style of the grid should be like this image.

All I have achieved so far is the following code which compresses all the variables/items into one column so they can together be portrayed on the y-axis - the id is of course included in its own column as are the values:

df_1 %>%
  select("Thr" = Thriving, "Stf" = Satisfaction, "Wb" = Wellbeing, "id" = id) %>%
  na.omit %>%
  gather(key = "variable", value = "value", -id) %>%

I am looking for a solution that works without storing the data in a new frame.

Also, I am looking for a solution that would be useful for even 100 or more respondents and up to about 40 variables. It would not matter if one rectangle would then be very small, I just want to have a nice colour play which would give a nice taste of where an organisation may be achieving low or high - and how it is achieving in general.

Thanks for reading, very grateful for any help!


Solution

  • There is probably a better graphics oriented approach, but you can do this with base plot and by treating your data as a raster:

    library(raster)
    df_1 <- cbind("Thriving" = c(2.33, 4.21, 6.37, 5.28, 4.87, 3.92, 4.16, 5.53), "Satisfaction" = c(3.45, 4.53, 6.01, 3.87, 2.92, 4.50, 5.89, 4.72), "Wellbeing" = c(2.82, 3.45, 5.23, 3.93, 6.18, 4.22, 3.68, 4.74), "id" = c(1:8))
    r <- raster(ncol=nrow(df_1), nrow=3, xmn=0, xmx=8, ymn=0, ymx=3)
    values(r) <- as.vector(as.matrix(df_1[,1:3]))
    plot(r, axes=F, box=F, asp=NA)
    axis(1, at=seq(-0.5, 8.5, 1), 0:9)
    axis(2, at=seq(-0.5, 3.5, 1), c("", colnames(df_1)), las=1)
    

    enter image description here