首页 > 解决方案 > 基础 R 图:帮助减少多个图之间的空间

问题描述

我试图在一个窗口中减少多个绘图之间的空间量,但无法实现我想要的。情节和代码如下。我想将图例保留在原处,但减少 B 和 C 之间的空间。如何将图 C(向左)移动到靠近图 B 以模拟 A 和 B 之间的间距,同时保持图例到位.. .我希望传奇独立而不是情节。PS 我喜欢基本的 R 绘图函数绘图的方式,并且不打算转换为使用 ggplot。阴谋

# p1
par(mfrow=c(1,3))
par(oma = c(1.5,3.5,0,0))
par(mar = c(4,6.5,4,0))
xaxis<-1:7
plot(xaxis, p1, type = "b", pch = 19, col = "red",xlab = "", ylab = "", main = "",ylim = c(1000,30000), xaxt = 'n', yaxt ='n')
points(xaxis, p1.1, col ="blue", pch = 19)
lines(xaxis, p1.1, col = "blue", type ="b")
axis(1, at = 1:7, labels = c(2,4,6,8,10,12,20), las = 1)
axis(2, at = seq(500, 31000, by = 1500), las=2)
mtext("(A)",side=3,line=-1.5, adj = 1,cex=1)
# p2
par(mar = c(4,0.5,4,6))
plot(xaxis, p2, type = "b", pch = 19, col = "red",xlab = "", ylab = "", main = "",ylim = c(1000,30000), xaxt = 'n', yaxt ='n')
points(xaxis, p2.1, col ="blue", pch = 19)
lines(xaxis, p2.1, col = "blue", type ="b")
axis(1, at = 1:7, labels = c(2,4,6,8,10,12,20), las = 1)
mtext("(B)",side=3,line=-1.5, adj = 1,cex=1)
# p3
par(mar = c(4,0.5,4,6))
plot(xaxis, p3, type = "b", pch = 19, col = "red",xlab = "", ylab = "", main = "",ylim = c(1000,30000), xaxt = 'n', yaxt ='n')
points(xaxis, p3.1, col ="blue", pch = 19)
lines(xaxis, p3.1, col = "blue", type ="b")
axis(1, at = 1:7, labels = c(2,4,6,8,10,12,20), las = 1)
mtext("(C)",side=3,line=-1.5, adj = 1,cex=1)

# axes labels
mtext("Y",side=2,line=0,outer = TRUE,cex=1)
mtext("X[enter image description here][1]",side=1,line=0,,cex=1,outer= TRUE, las=0)
legend("right", legend = c("blah 1", "blah 2"),col = c("red", "blue"), bty = "n", xpd=TRUE, mar(c(7,7,7,7)), cex = 1, pch = 19)

标签: rplot

解决方案


全部 删除par(mar(...))mai改用。请参阅此 SO 帖子,其中包含一个使用的解决方案mai和另一个使用mar.

old_par <- par(
  mfrow = c(1, 3), 
  mai = c(1, 0.1, 0.1, 0.1), 
  oma = c(1.5, 3.5, 0, 0)
)

# rest of code is the same

par(old_par)

在此处输入图像描述


测试数据创建代码

set.seed(2021)
p1 <- p2 <- p3 <- cumsum(rnorm(7))*10000
p1.1 <- p2.1 <- p3.1 <- cumsum(rnorm(7))*10000

推荐阅读