在R中以编程方式创建图形矩阵

问题描述

我想创建一个5x5的图形矩阵,这些矩阵在下面的np变量上循环。将25个“小倍数”排列成一个图形。可以在ggplot2中完成,但也欢迎使用非ggplot解决方案。

这是我的起点:

n <- 1000
p <- 0.01
bd1 <- rbinom(n,n,p)
bins <- seq(min(bd1),max(bd1),1) # optional count bins

ggplot() + geom_histogram(aes(x = bd1,y =..count..),breaks = bins)

count_vector <- c(10,50,100,500,1000)
prob_vector <- c(0.005,0.01,0.05,0.1,0.5)

做到这一点的最佳方法是什么?

解决方法

这是使用gridExtraggplot2的一种方法。但是,有多个软件包可以执行此操作:

library(ggplot2)
library(gridExtra)

make_plot <- function(count,prob) {
  bd1 <- rbinom(count,count,prob)
  bins <- seq(min(bd1),max(bd1),1) # optional count bins
  
  ggplot() + geom_histogram(aes(x = bd1,y =..count..),breaks = bins) + 
    ggtitle(sprintf("count = %s\nprob = %s",as.character(count),as.character(prob)))
}

count_vector <- c(10,50,100,500,1000)
prob_vector <- c(0.005,0.01,0.05,0.1,0.5)

nrows <- length(count_vector)
ncols <- length(prob_vector)

plots <- matrix(list(),nrows,ncols)
for (i in seq_along(count_vector)) for (j in seq_along(prob_vector)) {
   plots[[i,j]] <- make_plot(count_vector[i],prob_vector[j])
}

grid.arrange(arrangeGrob(grobs = plots))

最后一条语句给了我

enter image description here

左上图失败了,但这与输入参数有关。

,

我建议使用patchwork方法并使用循环。我对您的代码进行了些微更改,以使用数据框,因为此数据更适合patchwork方法wrap_plots()。这里的代码:

library(patchwork)
library(ggplot2)

#Vectors
count_vector <- c(10,0.5)
#Data
df <- data.frame(count_vector,prob_vector=rep(prob_vector,each=5))
#Create a list
List <- list()
#Loop for plots
for(i in 1:dim(df)[1])
{
  set.seed(123)
  #Code
  bd1 <- data.frame(v1=rbinom(df$count_vector[i],df$count_vector[i],df$prob_vector[i]))
  bins <- seq(min(bd1$v1),max(bd1$v1),1)
  #Plot
  L <- ggplot(bd1,aes(x=v1)) +
  geom_histogram(aes(y =..count..),breaks = bins)+
  labs(title = paste0('N = ','\np = ',df$prob_vector[i]))
  #Assign to list
  List[[i]] <- L
}
#Final plot
wrap_plots(List,ncol = 5)

输出:

enter image description here