Search code examples
rggplot2ggpairs

ggpairs labels on bar plots


I am wondering if there is a way to add labels on top of bar plots and grouped bar plots in ggpairs,

library(GGally)
data(diamonds, package="ggplot2")
diamonds.samp <- diamonds[sample(1:dim(diamonds)[1], 1000), ]

    pm <- ggpairs(
      diamonds.samp[, 1:5],
      mapping = ggplot2::aes(color = cut),
      upper = list(continuous = wrap("density", alpha = 0.5), combo = "box_no_facet"),
      lower = list(continuous = wrap("points", alpha = 0.3), combo = wrap("dot_no_facet", alpha = 0.4)),
      title = "Diamonds"
    )
    pm

enter image description here


Solution

  • Sure is this possible. One option would be to extend the default plotting function by adding a geom_text layer to add the labels:

    library(GGally)
    
    set.seed(123)
    
    data(diamonds, package = "ggplot2")
    
    diamonds.samp <- diamonds[sample(nrow(diamonds), 1000), ]
    
    bar_label <- function(data,
                             mapping,
                             ...) {
      ggally_barDiag(
        data,
        mapping
      ) +
        geom_text(
          aes(
            label = after_stat(count)
          ),
          stat = "count",
          position = position_stack(vjust = 1),
          vjust = 1
        )
    }
    
    pm <- ggpairs(
      diamonds.samp[, 1:5],
      mapping = ggplot2::aes(color = cut),
      upper = list(continuous = wrap("density", alpha = 0.5), combo = "box_no_facet"),
      lower = list(continuous = wrap("points", alpha = 0.3), combo = wrap("dot_no_facet", alpha = 0.4)),
      diag = list(discrete = wrap(bar_label)), title = "Diamonds"
    )
    pm
    

    enter image description here