7

I wanted to make a ggpairs plot of the mtcars data set, but I only care about the relationship between mpg and all the other variables, not between all of the variables and all of the variables.

I changed some of the columns to factors

mtcars$cyl = as.factor(mtcars$cyl)
mtcars$vs = as.factor(mtcars$vs)
mtcars$am = as.factor(mtcars$am)
mtcars$gear = as.factor(mtcars$gear)
mtcars$carb = as.factor(mtcars$carb)

and rand the plot

ggpairs(mtcars, colour = "am", columns = c(1,2,8:11))

Is there any way I can show just the first row of the plot?

zx8754
  • 52,746
  • 12
  • 114
  • 209
Zornosaur
  • 71
  • 1
  • 2
  • 1
    I'd say it won't be easy: take a look at a [similar question](http://stackoverflow.com/questions/24135157/arranging-ggally-plots-with-gridextra) and my explanation. – tonytonov Feb 25 '15 at 09:51

2 Answers2

3

Based on tonytonov's answer, I explored the ggpairs output and found some attributes that you can modify to get the desired result:

gplot <- GGally::ggpairs(data)
gplot$nrow <- 1
gplot$yAxisLabels <- a$yAxisLabels[1]
print(gplot)

That should render only the first row of plots. I don't think there is an easy way to get a single row that's not the first one, since $nrow acts like an upper limit, but simply reordering your columns should do the trick.

overdisperse
  • 416
  • 3
  • 13
3

There's any easier way to select a row from ggpairs output using GGally's own getPlot() and ggmatrix(). To select a row by number (like the first) just specify i = 1 in getPlot().

library(ggplot2)
library(GGally)

pairs <- ggpairs(mtcars, columns = c(1,2,8:11))
plots <- lapply(1:pairs$ncol, function(j) getPlot(pairs, i = 1, j = j))
ggmatrix(
    plots,
    nrow = 1,
    ncol = pairs$ncol,
    xAxisLabels = pairs$xAxisLabels,
    yAxisLabels = primary_var
)

With slightly more work you could select the row using the primary variable of interest. Just set primary_var to the name of the variable you want in the following code:

library(ggplot2)
library(GGally)

primary_var <- "mpg"
pairs <- ggpairs(mtcars, columns = c(1,2,8:11))
pvar_pos <- match(primary_var, pairs$xAxisLabels)
plots <- lapply(1:pairs$ncol, function(j) getPlot(pairs, i = pvar_pos, j = j))
ggmatrix(
    plots,
    nrow = 1,
    ncol = pairs$ncol,
    xAxisLabels = pairs$xAxisLabels,
    yAxisLabels = primary_var
)

NOTE: Almost any row you choose will by default have 1+ empty plots with only the correlation between variables in it. You can change that by changing the upper argument in ggpairs(). Check the documentation for details.

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
Allen Baron
  • 153
  • 1
  • 9