以一个Plot绘制五行六列共30个图,然后每30个图单元包含两个图为例:
如下图所示:
代码如下:
for (i in 1:(5*6)) {create_subplots <- function() {library(ggplot2)library(dplyr)library(tidyr)# 创建一个随机的数据框simulated_data <- data.frame(V1 = rnorm(100, mean = 0, sd = sqrt(0.5)), # 生成均值为 mean,标准差为 sd 的正态分布随机值V2 = rgamma(100, shape = 2, scale = 1), # 生成伽马分布随机值,shape 为形状参数,scale 为尺度参数V3 = runif(100, min = 0, max = 1), # 生成均值为 mean,标准差为 sd 的正态分布随机值V4 = rpois(100, lambda = 5), # 生成泊松分布随机值,lambda 为泊松分布的参数V5 = rexp(100, rate = 0.5), # 生成指数分布随机值,rate 为指数分布的参数V6 = rbinom(100, size = 10, prob = 0.1) # 生成二项分布随机值,size 为试验次数,prob 为成功的概率)simulated_data <- simulated_data %>%rename(Case1 = V1,Case2 = V2,Case3 = V3,Case4 = V4,Case5 = V5,Case6 = V6)simulated_data_long <- gather(simulated_data, key = "variable", value = "value")# 创建一个含有多个琴图的图表,每个琴图对应数据的一个列p1 <- ggplot(simulated_data_long, aes(x = variable, y = value)) +geom_violin(alpha = 0.5, size = 0.1) +# 调整透明度和线条宽度geom_boxplot(fill = "gray", alpha = 0.04, width = 0.02) +# 调整透明度和线条宽度geom_jitter(aes(color = variable), width = 0.02, alpha = 0.7, size = 0.03) +# 调整透明度和点的大小labs(x = " ",y = "",title = " ") +scale_color_discrete(name = " ") +theme_minimal() +facet_wrap(~ variable, scales = "free")+theme(strip.text = element_blank(),legend.text = element_text(size = 0.12), # 调整图例文本大小legend.title = element_text(size = 0.15), # 调整图例标题大小legend.key.size = unit(1.5, "lines"), # 调整图例间距大小axis.title.y = element_text(size = 0.18) # 调整Y轴标签的字体大小) + theme(legend.position = "none", axis.title.x = element_blank(), axis.title.y = element_blank(), axis.text.x = element_blank(), axis.text.y = element_blank(), axis.ticks.x = element_blank(), axis.ticks.y = element_blank() )library(ggstatsplot)# 绘制分组箱线图p2 <- ggplot(iris, aes(x = Species, y = Sepal.Length)) +geom_boxplot() +theme(legend.position = "none", axis.title.x = element_blank(),axis.title.y = element_blank(), axis.text.x = element_blank(), axis.text.y = element_blank(), axis.ticks.x = element_blank(), axis.ticks.y = element_blank() )subplot <- p1 / p2 return(subplot)}main_plot_list[[i]] <- create_subplots()
}main_plot <- wrap_plots(main_plot_list, ncol = 6)print(main_plot)