Zornosaur
Zornosaur

Reputation: 81

Printing a single row from a ggpairs plot

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?

Upvotes: 8

Views: 3905

Answers (2)

Allen Baron
Allen Baron

Reputation: 153

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.

Upvotes: 3

overdisperse
overdisperse

Reputation: 426

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.

Upvotes: 3

Related Questions