gpt4 book ai didi

r - ggplot2 的组合图(不在单个图中),使用 par() 或 layout() 函数?

转载 作者:行者123 更新时间:2023-12-03 10:50:34 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Creating arbitrary panes in ggplot2

(5 个回答)


6年前关闭。




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

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

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

这是 Quick-R 的示例,链接: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 并结合绘图时,我没有得到输出。

最佳答案

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))

关于r - ggplot2 的组合图(不在单个图中),使用 par() 或 layout() 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9490482/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com