rggplot2categorical-dataternaryggtern

Color tiles (triangles) of a categorical ternary/simplex plot according to numeric values


I have a data set with combinations of 3 categorical variables (each with 6 classes) and a continuous value (ranging from 0 to 1) that belongs to these class combinations. In R, this data looks like this (example data):

grid <- expand.grid(letters[1:6], letters[1:6], letters[1:6])[, 3:1]
grid$vals <- runif(nrow(grid), 0, 1)

Now I'm going to visualize this data. My plan was to create a ternary (syn. simplex) plot for the three categorical variables ("Var3", "Var2" and "Var1") and color the 216 triangles belonging to each combination of categories according to the values in the variable "vals". It would be great if the color code would range from red (value of 0) via white (value of 0.5) to blue (value of 1).

Unfortunately I already struggle a lot creating a simple ternary plot with 6 categories per variable. Thus, I'd be very happy if you'd recommend a solution. Thanks a lot in advance!


Solution

  • Something like this?

    # adapted from the documentation example: https://ggplot2.tidyverse.org/reference/scale_gradient.html
    
    library(ggtern)
    set.seed(1)
    
    library(tidyverse)
    library(ggtern)
    grid %>% 
      mutate(across(starts_with("Var"), as.numeric)) %>%
      ggtern(aes(Var1, Var2, Var3)) +
       geom_tri_tern(bins=10,aes(fill=after_stat(count))) + 
       scale_fill_gradientn(colors = c("red", "white", "blue"), 
                            values = c(0, 0.5, 1))
    

    ternary plot