Как настроить линии в ggpairs [GGally]

У меня есть следующий сюжет:

введите здесь описание изображения

Генерируется с помощью этого кода:

library("GGally")
data(iris)
ggpairs(iris[, 1:4], lower=list(continuous="smooth", params=c(colour="blue")),
  diag=list(continuous="bar", params=c(colour="blue")), 
  upper=list(params=list(corSize=6)), axisLabels='show')

Мои вопросы:

  1. Как я могу изменить линию корреляции на red, теперь она черная.
  2. А линия корреляции скрыта под диаграммой рассеяния. Я хочу поставить его сверху. Как я могу это сделать?

person neversaint    schedule 16.06.2015    source источник
comment
Вы можете управлять прозрачностью точек на точечной диаграмме, добавляя alpha=0.3 к параметрам нижнего списка. Это поможет больше сфокусировать плавные линии.   -  person nehiljain    schedule 16.06.2015
comment
@nehiljain: Нет, так не пойдет. Когда точечная диаграмма плотная, линия все равно будет скрыта. Я думал об этой строке . Но не знаю, как это реализовать в ggpairs.   -  person neversaint    schedule 16.06.2015


Ответы (2)


Я надеюсь, что есть более простой способ сделать это, но это своего рода подход грубой силы. Однако это дает вам гибкость, позволяющую легко настраивать графики. Суть в том, чтобы использовать putPlot для размещения на рисунке графика ggplot2.

library(ggplot2)

## First create combinations of variables and extract those for the lower matrix
cols <- expand.grid(names(iris)[1:4], names(iris)[1:3])    
cols <- cols[c(2:4, 7:8, 12),]  # indices will be in column major order

## These parameters are applied to each plot we create
pars <- list(geom_point(alpha=0.8, color="blue"),              
             geom_smooth(method="lm", color="red", lwd=1.1))

## Create the plots (dont need the lower plots in the ggpairs call)
plots <- apply(cols, 1, function(cols)                    
    ggplot(iris[,cols], aes_string(x=cols[2], y=cols[1])) + pars)
gg <- ggpairs(iris[, 1:4],
              diag=list(continuous="bar", params=c(colour="blue")), 
              upper=list(params=list(corSize=6)), axisLabels='show')

## Now add the new plots to the figure using putPlot
colFromRight <- c(2:4, 3:4, 4)                                    
colFromLeft <- rep(c(1, 2, 3), times=c(3,2,1))
for (i in seq_along(plots)) 
    gg <- putPlot(gg, plots[[i]], colFromRight[i], colFromLeft[i])
gg

введите здесь описание изображения

## If you want the slope of your lines to correspond to the 
## correlation, you can scale your variables
scaled <- as.data.frame(scale(iris[,1:4]))
fit <- lm(Sepal.Length ~ Sepal.Width, data=scaled)
coef(fit)[2]
# Sepal.Length 
#  -0.1175698 

## This corresponds to Sepal.Length ~ Sepal.Width upper panel

Редактировать

Чтобы обобщить функцию, которая принимает любые индексы столбцов и строит тот же график

## colInds is indices of columns in data.frame
.ggpairs <- function(colInds, data=iris) {
    n <- length(colInds)
    cols <- expand.grid(names(data)[colInds], names(data)[colInds])
    cInds <- unlist(mapply(function(a, b, c) a*n+b:c, 0:max(0,n-2), 2:n, rep(n, n-1)))
    cols <- cols[cInds,]  # indices will be in column major order

    ## These parameters are applied to each plot we create
    pars <- list(geom_point(alpha=0.8, color="blue"),              
                 geom_smooth(method="lm", color="red", lwd=1.1))

    ## Create the plots (dont need the lower plots in the ggpairs call)
    plots <- apply(cols, 1, function(cols)                    
        ggplot(data[,cols], aes_string(x=cols[2], y=cols[1])) + pars)
    gg <- ggpairs(data[, colInds],
                  diag=list(continuous="bar", params=c(colour="blue")), 
                  upper=list(params=list(corSize=6)), axisLabels='show')

    rowFromTop <- unlist(mapply(`:`, 2:n, rep(n, n-1)))
    colFromLeft <- rep(1:(n-1), times=(n-1):1)
    for (i in seq_along(plots)) 
        gg <- putPlot(gg, plots[[i]], rowFromTop[i], colFromLeft[i])
    return( gg )
}

## Example
.ggpairs(c(1, 3))
person Rorschach    schedule 16.06.2015
comment
@Legalizelt: Как я могу обобщить ваш код в функцию, чтобы она могла принимать данные с любым количеством столбцов? (т.е. теперь вы предполагаете 4 столбца) - person neversaint; 16.06.2015
comment
Это не должно быть слишком сложно, просто нужно обобщить индексы, я могу попробовать. - person Rorschach; 16.06.2015
comment
@Legalizelt: colFromRight ты имеешь в виду rowFromTop? - person neversaint; 16.06.2015
comment
Вы можете попробовать эту функцию - person Rorschach; 16.06.2015

Проверьте свою версию GGally до packageVersion("GGally") и обновите GGally до версии 1.0.1

library("GGally")
library("ggplot2")
data(iris)

lowerFn <- function(data, mapping, method = "lm", ...) {
  p <- ggplot(data = data, mapping = mapping) +
    geom_point(colour = "blue") +
    geom_smooth(method = method, color = "red", ...)
  p
}

ggpairs(
  iris[, 1:4], lower = list(continuous = wrap(lowerFn, method = "lm")),
  diag = list(continuous = wrap("barDiag", colour = "blue")),
  upper = list(continuous = wrap("cor", size = 10))
)

введите описание изображения здесь

person WCC    schedule 15.03.2016