如何使用R在单个图中绘制数据框中变量的散点图和所有其他变量?

时间:2017-07-24 07:15:30

标签: r ggally

我尝试在GGally中使用ggpairs来绘制散点图。但它绘制了每个变量 与所有其他变量。我想绘制特定变量的散点图与数据帧中的所有其他变量,并显示每个散点图的相关值。 请帮我。 提前谢谢。

1 个答案:

答案 0 :(得分:1)

答案实际上是一个谷歌搜索,但这里有。

library(ggplot2)
library(grid)

# google search: "multiplot ggplot2"
# http://www.cookbook-r.com/Graphs/Multiple_graphs_on_one_page_(ggplot2)/
multiplot <- function(..., plotlist=NULL, file, cols=1, layout=NULL) {


    # Make a list from the ... arguments and plotlist
    plots <- c(list(...), plotlist)

    numPlots = length(plots)

    # If layout is NULL, then use 'cols' to determine layout
    if (is.null(layout)) {
        # Make the panel
        # ncol: Number of columns of plots
        # nrow: Number of rows needed, calculated from # of cols
        layout <- matrix(seq(1, cols * ceiling(numPlots/cols)),
                         ncol = cols, nrow = ceiling(numPlots/cols))
    }

    if (numPlots==1) {
        print(plots[[1]])

    } else {
        # Set up the page
        grid.newpage()
        pushViewport(viewport(layout = grid.layout(nrow(layout), ncol(layout))))

        # Make each plot, in the correct location
        for (i in 1:numPlots) {
            # Get the i,j matrix positions of the regions that contain this subplot
            matchidx <- as.data.frame(which(layout == i, arr.ind = TRUE))

            print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row,
                                            layout.pos.col = matchidx$col))
        }
    }
}

# some dummy data
x <- as.data.frame(matrix(rnorm(100), 10, 10))

# plot the first variable against all others
plotList <- list()
for (i in 1:9) {
    plotList[[i]] <- ggplot(data = x, aes_(x = x[, 1], y = x[, i+1])) + geom_point() + xlab("x") + ylab("y")
}

# actually draw the multiplot
multiplot(plotlist = plotList, cols = 3)