rggplot2ggallyggpairs

Different scale units for different graphs with R's GGally ggpairs


Using iris dataset for the example here, I have the following grid of graphs from ggpairs():

library(GGally)
ggpairs(iris)

enter image description here ...

I would like to clean this graph up a bit, in particular with some formatting on the axes. I would like to bold the titles (Sepal.Length, Sepal.Width, etc.), and more importantly, I would like to format the units on the axes.

However, for each column / row, I would like to use different unit formatting. (even though it's not a percentage-based stat), for the Sepal.Width column / row, I'd like the units to be percentages. With a normal ggplot() with a continuous variable, I would do scale_x_continuous(labels = scales::percent_format()), however I'm not quite sure how to selectively apply unit formatting to different rows / columns of the ggpairs() output.

Any help with this is greatly appreciated, thanks!


Solution

  • There are a couple of ways to proceed; here are two.

    You can alter the specific plots by using the subsetting mechanism:

    library(GGally)
    p = ggpairs(iris)
    p[2,1] = p[2,1] + scale_y_continuous(labels = scales::percent_format())
    

    or you can write a function to pass to ggpairs where you can specify formats dependent on the variable. A silly example to format the y-axes:

    # acc_y is a named vector giving the parameters to be passed to 
    # the accuracy argument of scales::percent_format
    quick_fun <- function(data, mapping, acc_y, ...){
    
        y_name = quo_name(mapping$y)
    
        ggplot(data=data, mapping=mapping) + 
          geom_point() + 
          scale_y_continuous(labels = scales::percent_format(accuracy = acc_y[y_name])) 
      }
    
    ggpairs(iris, lower=list(continuous=wrap(quick_fun, 
                                             acc_y=c("Sepal.Length"=0.1, "Sepal.Width"=0.1, 
                                                     "Petal.Length"=10, "Petal.Width"=1000))))
    

    Also note that ggplot themes also work on the plot matrix, so you can format the strip text

    p + theme(strip.text = element_text(face="bold", colour="red", size=20))