[英]Create a matrix of plots programatically in R
我想创建一个 5x5 的图矩阵,它在下面的n
和p
变量上循环。 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)
做这个的最好方式是什么?
这是使用gridExtra
和ggplot2
执行此操作的一种方法。 有多个包可以做到这一点:
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))
最后一句话给了我:
左上图失败,但这与输入参数有关。
我建议采用patchwork
方法并使用循环。 我对您的代码进行了轻微更改以使用数据帧,因为此数据更适合patchwork
方法wrap_plots()
。 这里的代码:
library(patchwork)
library(ggplot2)
#Vectors
count_vector <- c(10,50,100,500,1000)
prob_vector <- c(0.005, 0.01, 0.05, 0.1, 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 = ',df$count_vector[i],'\np = ',df$prob_vector[i]))
#Assign to list
List[[i]] <- L
}
#Final plot
wrap_plots(List,ncol = 5)
输出:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.