Plot every 3 columns (as x,y,z) in a data frame function

60 Views Asked by At

I have a data frame with 3 ternary axes for each triad like the following toy example

library(ggtern)
library(compositions)

dummy <- data.frame(
  t1 = rDirichlet.acomp(100, alpha = c(x=15,y=7,z=3)),
  t2 = rDirichlet.acomp(100, alpha = c(x=15,y=7,z=3)),
  t3 = rDirichlet.acomp(100, alpha = c(x=15,y=7,z=3)),
  t4 = rDirichlet.acomp(100, alpha = c(x=15,y=7,z=3)),
  t5 = rDirichlet.acomp(100, alpha = c(x=15,y=7,z=3)),
  t6 = rDirichlet.acomp(100, alpha = c(x=15,y=7,z=3))
)

My objective is to grab each 3 columns (x,y,z) for each triad (t1, t2, t3, etc..) and plot them using the library ggtern::ggtern()

First I create this regex vector:

regex <- paste0('^t', 1:6)

Then loop over it and combine that with grep to grab each set of 3 columns and then somehow plot them.

So on first iteration of the loop we grep t1

grep(regex[1], names(dummy), value = TRUE)

Here is what the plot function looks like for one triad:

ggtern(
  data = dummy, mapping = aes(
  x = dummy[[1]],
  y = dummy[[2]],
  z = dummy[[3]]
  
)) + ggtern_custom() +
  Tlab(names(dummy[1])) +
  Llab(names(dummy[2])) +
  Rlab(names(dummy[3]))

Don't worry about the ggtern_custom() that's a helper function to make the plot looks better.

The final goal is to plot all 6 of them not just 1 and arrange them together (not manually, but using a function/loop)

Could you help me finish this idea? Any other approach? I'd prefer a base R solution.

1

There are 1 best solutions below

1
DaveArmstrong On

What about this:

library(ggtern)
library(compositions)
library(tidyr)
library(dplyr)

dummy <- data.frame(
  t1 = rDirichlet.acomp(100, alpha = c(x=15,y=7,z=3)),
  t2 = rDirichlet.acomp(100, alpha = c(x=15,y=7,z=3)),
  t3 = rDirichlet.acomp(100, alpha = c(x=15,y=7,z=3)),
  t4 = rDirichlet.acomp(100, alpha = c(x=15,y=7,z=3)),
  t5 = rDirichlet.acomp(100, alpha = c(x=15,y=7,z=3)),
  t6 = rDirichlet.acomp(100, alpha = c(x=15,y=7,z=3))
)

dummy_long <- dummy %>% pivot_longer(everything(), names_pattern="(t\\d).([x-z])", 
                       names_to = c("var", ".value"))

ggtern(dummy_long, aes(x=x, y=y, z=z)) + 
  geom_point() + 
  facet_wrap(~var)

Created on 2022-02-17 by the reprex package (v2.0.1)