0

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

4

1 回答 1

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)
于 2017-07-24T07:27:20.713 回答