Search code examples
rggplot2ggallyggpairs

How to save a customized (only the lower triangle retained) ggpairs graph?


I used the gpairs_lower function from this answer to show only the lower triangle of a ggpairs matrix of plots. But now I have no idea how to save the resulting plot.

The usual method to save a ggpairs plot does not work here:

gpairs_lower <- function(g){
  g$plots <- g$plots[-(1:g$nrow)]
  g$yAxisLabels <- g$yAxisLabels[-1]
  g$nrow <- g$nrow -1

  g$plots <- g$plots[-(seq(g$ncol, length(g$plots), by = g$ncol))]
  g$xAxisLabels <- g$xAxisLabels[-g$ncol]
  g$ncol <- g$ncol - 1

  g
}

library("GGally")
g <- ggpairs(iris[, 1:4], 
             lower  = list(continuous = "points"),
             upper  = list(continuous = "blank"),
             diag  = list(continuous = "blankDiag")
     )


png("graph.png", height = 720, width = 720)
gr <- gpairs_lower(g)
print(gr)
dev.off()

## graph.png is not saved

It doesn't work, I believe, because gpairs_lower as opposed to ggpairs does not return a ggmatrix object.

Richard Any help would be appreciated.

EDIT: Now the code above works!


Solution

  • The issue with your code is that the default unit of height and width is pixels, so you are saving a 7x7 pixel image!! Try other values or change units:

    png("myPlotMatrix.png", height = 700, width = 700)
    g <- ggpairs(iris[, 1:4], 
                 lower  = list(continuous = "points"),
                 upper  = list(continuous = "blank"),
                 diag  = list(continuous = "blankDiag")
    )
    
    g<-gpairs_lower(g)
    print(g)
    dev.off()
    

    Look at ?png:

    width: the width of the device.

    height: the height of the device.

    units: The units in which height and width are given. Can be px (pixels, the default), in (inches), cm or mm.