Search code examples
rggally

accessing panel specific variables in ggpairs custom function


I'm wanting to add an annotation/geom on my panel functions with the content dependent on the row and column for example I might want to print the text: "Row: i, Column: j" in addition to normal density plots.

...something like this...

  library(data.table)
  library(ggplot2)
  library(GGally)

  dt <- as.data.table(diamonds)[sample(.N, 50),(carat, depth, x, y, z)]
  
  # custom x-y scatter w/PC vectors
  custom_plot <- function(data, mapping, i, j, ...) {
    
    ggplot(data = data, mapping = mapping) + 
      geom_point(...) +
      annotate("text", x = -1, y = 1, label = as.character(i)) + 
      annotate("text", x = 1, y = -1, label = as.character(j)) + 
      theme_minimal()
  }
  
  ggpairs(dt,
                upper = list(continuous = wrap(pcplot)),
                diag = list(continuous = "blank"),
                lower = list(continuous = wrap(custom_plot))
  )

Edit: I've looked at the source - the row and column information is unavailable to the custom plotting function which gets wrapped with just the formal arguments that were specified


Solution

  • You could unquote the current x and y axes to figure out your row and column using match(). Then place the labels depending on your current data min(data[[x_var]]). Note: since this is a bit hacky, this works so long you don't play around with the columns parameter in ggpairs.

    library(data.table)
    library(ggplot2)
    library(GGally)    
    dt <- as.data.table(diamonds)[sample(.N, 50), .(carat, depth, x, y, z)]
    
    custom_plot <- function(data, mapping, ...) {
      x_var <- quo_name(mapping$x)
      y_var <- quo_name(mapping$y)
     
      gg <- ggplot(data = data, mapping = mapping) + 
        geom_point(...) +
        annotate("text", 
                 x = min(data[[x_var]]), 
                 y = min(data[[y_var]]), 
                 label = paste("Row:", match(y_var, colnames(dt)), " Column:", match(x_var, colnames(dt))), vjust = 0.4, hjust = -0.4, size = 3) +
        theme_minimal()
    }
    
    ggpairs(dt, lower = list(continuous = wrap(custom_plot)))
    

    giving

    out