本文介绍了ggplot2 的组合图(不在单个图中),使用 par() 或 layout() 函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在考虑使用 par() 或 layout() 函数来组合 ggplots.可以使用这些功能吗?

I've been thinking of using par() or layout() functions for combining ggplots. Will it be possible to use those functions?

假设我想绘制散点图的 ggplot 和直方图的 ggplot.我想结合这两个图(不是在一个单一的情节).是否适用?

Say I want to plot ggplot for scatterplot and ggplot for histogram. And I want to combine the two plots (NOT IN A SINGLE PLOT). Is it applicable?

我用 R 中的简单绘图进行了尝试,没有使用 ggplot 函数.它确实有效.

I tried it with simple plotting in R, without using the ggplot functions. And it works actually.

这是 Quick-R 的示例,链接:http://www.statmethods.net/advgraphs/layout.html

Here's a sample from Quick-R, Link: http://www.statmethods.net/advgraphs/layout.html

# 4 figures arranged in 2 rows and 2 columns
attach(mtcars)
par(mfrow=c(2,2))
plot(wt,mpg, main="Scatterplot of wt vs. mpg")
plot(wt,disp, main="Scatterplot of wt vs disp")
hist(wt, main="Histogram of wt")
boxplot(wt, main="Boxplot of wt")

# One figure in row 1 and two figures in row 2
attach(mtcars)
layout(matrix(c(1,1,2,3), 2, 2, byrow = TRUE))
hist(wt)
hist(mpg)
hist(disp)

但是当我尝试使用 ggplot 并组合绘图时,我没有得到输出.

But when I try to use ggplot, and combine the plot, I don't get an output.

推荐答案

library(ggplot2)
library(grid)


vplayout <- function(x, y) viewport(layout.pos.row = x, layout.pos.col = y)


plot1 <- qplot(mtcars,x=wt,y=mpg,geom="point",main="Scatterplot of wt vs. mpg")
plot2 <- qplot(mtcars,x=wt,y=disp,geom="point",main="Scatterplot of wt vs disp")
plot3 <- qplot(wt,data=mtcars)
plot4 <- qplot(wt,mpg,data=mtcars,geom="boxplot")
plot5 <- qplot(wt,data=mtcars)
plot6 <- qplot(mpg,data=mtcars)
plot7 <- qplot(disp,data=mtcars)

# 4 figures arranged in 2 rows and 2 columns
grid.newpage()
pushViewport(viewport(layout = grid.layout(2, 2)))
print(plot1, vp = vplayout(1, 1))
print(plot2, vp = vplayout(1, 2))
print(plot3, vp = vplayout(2, 1))
print(plot4, vp = vplayout(2, 2))


# One figure in row 1 and two figures in row 2
grid.newpage()
pushViewport(viewport(layout = grid.layout(2, 2)))
print(plot5, vp = vplayout(1, 1:2))
print(plot6, vp = vplayout(2, 1))
print(plot7, vp = vplayout(2, 2))

这篇关于ggplot2 的组合图(不在单个图中),使用 par() 或 layout() 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 18:00