Search code examples
rggplot2geom-textggallyggpairs

ggpairs what is the name of the column with the facets?


I am trying to add text to a ggpairs plot. I have created my own data frame with columns for the x and y positions and the labels. However, I do not know what to name the column that contains the facet labels.

In the context of the example below: I want each label to show up on only one facet. To achieve this, what should I call GROUP_VAR?

plot_my_bars <-  function(data,
                          mapping,
                          ...){

    bars_plot <- ggally_barDiag(data,
                                mapping) +
        geom_text(data = my_text_df,
                  aes(x = my_x,
                      y = my_y,
                      label = my_label))
    return(bars_plot)
}

my_df <- data.frame(var_1 = runif(10, 1, 2),
                    var_2 = runif(10, 1, 3))

my_text_df <- data.frame(my_x = c(0.5, 1),
                         my_y = c(2, 3),
                         my_label = c("lab1", "lab2"),
                         GROUP_VAR = c("var_1", "var_2"))

my_plot <- ggpairs(my_df,
                   upper = list(continuous = "blank"),
                   lower = list(continuous = "blank"),
                   diag = list(continuous = GGally::wrap(
                                                        plot_my_bars))
)


Solution

  • One option to achieve your desired result would be to filter the dataset passed to geom_text for the variable mapped on the x aes like so:

    library(GGally)
    
    set.seed(123)
    
    plot_my_bars <- function(data,
                             mapping,
                             ...) {
      bars_plot <- ggally_barDiag(
        data,
        mapping
      )
      
      bars_plot <- bars_plot +
        geom_text(
          data = subset(my_text_df, GROUP_VAR %in% quo_name(bars_plot$mapping$x)),
          aes(
            x = my_x,
            y = my_y,
            label = my_label
          )
        )
      
      return(bars_plot)
    }
    
    ggpairs(my_df,
      upper = list(continuous = "blank"),
      lower = list(continuous = "blank"),
      diag = list(continuous = GGally::wrap(
        plot_my_bars
      ))
    ) 
    #> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
    #> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.