我正在学习如何使用R来创建带有循环的多个图,将它们放在一个图(或“画布”)上并保存图。我希望这个图是2x2的。这是我正在学习的教程:https://bookdown.org/ndphillips/YaRrr/creating-multiple-plots-with-a-loop.html
下面是我的代码:
library(yarrr)
# Create the loop.vector (all the columns)
loop.vector <- 1:4
png(file="saving_plot2.png",
width = 1500, height = 1200)
par(mfrow = c(2, 2)) # Set up a 2 x 2 plotting space
for (i in loop.vector) { # Loop over loop.vector
# store data in column.i as x
x <- examscores[,i]
# Plot histogram of x
hist(x,
main = paste("Question", i),
xlab = "Scores",
xlim = c(0, 100))
}
dev.off()这个图看起来不错,但是有没有办法控制/增加子图之间的间距,并在这个图的顶部添加一个主标题?我知道在基数R中创建一个图时,您会使用:par(mar=c(5,4,4,2) + 0.1),但我在这里已经使用了par()。
发布于 2021-07-01 05:29:52
mar和title是实现这一点的简单方法。Mar更改绘图的间距,标题设置标题:
library(yarrr)
loop.vector <- 1:4
png(file="saving_plot2.png",
width = 1500, height = 1200)
# Mar changes the spacing of each plot from bottom, left, top, right
par("mar"=c(3,4,4,2), mfrow = c(2, 2)) # Set up a 2 x 2 plotting space
for (i in loop.vector) { # Loop over loop.vector
# store data in column.i as x
x <- examscores[,i]
# Plot histogram of x
hist(x,
main = paste("Question", i),
xlab = "Scores",
xlim = c(0, 100))
}
# Sets the title
title("This is a title", line = -1, outer = TRUE)
dev.off()实际上,有许多方法可以获得与您正在寻找的图表类似的图表。有关多个解决方案和说明,请参阅以下链接:
常见标题:
Common main title of a figure panel compiled with par(mfrow)
增加间距:
https://stackoverflow.com/questions/68201231
复制相似问题