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

How to plot scatterplot of a variable in a dataframe with all other variables in a single plot using R?

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

答案确实是一个 google 搜索,但这里是。

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)