简体   繁体   English

如何在 R 中将多个子图添加到多行图中?

[英]How do I add multiple subplots into a multirow figure in R?

i need to overlay multiple subplots onto a single plot which is already contained inside a multirow figure (see image)我需要将多个子图覆盖到单个 plot 上,该子图已经包含在多行图中(见图)
the reason why i need subplots instead of screen layout is because the figure will be possibly multicolumn, also (a 5 by 3 plot, in total)我需要子图而不是screen布局的原因是因为该图可能是多列的(总共 5 x 3 plot)
there are packages which assist in doing subplots, but they break when you use multirow figures, and sequential subplots, except the first one, are rendered next to the overall figure border, not relative to the current row/column plot borders有一些包可以帮助绘制子图,但是当您使用多行图形时它们会中断,并且顺序子图(第一个除外)呈现在整个图形边框旁边,与当前行/列 plot 边框无关
i understand large packages such as ggplot2 allow this relatively easily, but base R plots are highly preferable我了解诸如 ggplot2 之类的大型软件包相对容易实现这一点,但基础 R 地块非常可取
所需的图形外观

UPD: the minimum reproducible example depicting the problem is here: UPD:描述问题的最小可重现示例如下:

require(Hmisc)

COL.1 <- c('red','orange','yellow'); COL.2 <- c('blue','green','turquoise')

SUBPLOT.FUN <- function(COL) {plot(rnorm(100), type='l', col=COL)}
PLOT.FUN <- function(i) {
  plot(rnorm(100),ylim=c(-1,1))
  subplot(SUBPLOT.FUN(COL.1[i]), 100,1, vadj=1,hadj=1,pars=list(mfg=c(1,i)))
  subplot(SUBPLOT.FUN(COL.2[i]), 100,-1,vadj=0,hadj=1,pars=list(mfg=c(1,i)))
}
plot.new(); par(mfrow=c(1,3))
for (i in 1:3) {
  PLOT.FUN(i)
}

which looks like that:看起来像这样:
在此处输入图像描述 while what is required is shown on the first image (meaning, EACH of the three plots must contain 3 subplots in their respective locations (along the right border, arranged vertically))而第一张图片上显示了所需的内容(意思是,三个地块中的每个地块必须在各自的位置包含 3 个子地块(沿着右边界,垂直排列))
NB either the figure is multirow or multicolumn (as depicted) does not matter注意无论该图是多行还是多列(如图所示)都没有关系

Something like this?像这样的东西? Inspired in this R-bloggers post .受此R-bloggers 帖子的启发。

# reproducible test data
set.seed(2022)
x <- rnorm(1000)
y <- rbinom(1000, 1, 0.5)
z <- rbinom(1000, 4, 0.5)

# save default values and prepare 
# to create custom plot areas
old_par <- par(fig = c(0,1,0,1))

# set x axis limits based on data
h <- hist(x, plot = FALSE)
xlim <- c(h$breaks[1] - 0.5, h$breaks[length(h$breaks)] + 2)

hist(x, xlim = xlim)

# x = c(0.6, 1)  right part of plot
# y = c(0.5, 1)  top part of plot
par(fig = c(0.6, 1, 0.5, 1), new = TRUE)  
boxplot(x ~ y)  

# x = c(0.6, 1)   right part of plot
# y = c(0.1, 0.6) bottom part of plot
par(fig = c(0.6, 1, 0.1, 0.6), new = TRUE)  
boxplot(x ~ z)


# put default values back
par(old_par)

Created on 2022-08-18 by the reprex package (v2.0.1)reprex package (v2.0.1) 于 2022 年 8 月 18 日创建

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM