使用ggplot2创建一个三面板图,其中一个面板跨越2列。

3

我有以下数据:

    df <- data.frame("Stat" = c("Var1","Var1","Var1","Var1","Var1","Var2","Var2","Var2","Var2","Var2","Var2","Var2","Var2","Var2","Var2","Var2","Var2","Var2","Var2","Var2","Var2","Var2","Var2","Var2","Var2","Var3","Var3","Var3","Var3","Var3","Var3","Var3","Var3","Var3","Var3"),

"Value" = c(0,1,2,3,4,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,1,2,3,4,5,6,7,8,9,10),

"n" = c(33,120,223,63,20,17,28,33,22, 35,41,53,44,55,59,39,33, 46,30,29,23,21,14,6,18,7,29,50,80,86,91,83,35,34, 20))

我想做的是将上述数据绘制成一个柱状图,但分为三行(1列x3行)显示,每个面板只包含一个变量(Stat),例如第一个面板中只有Var1的图表,第二个面板中只有Var2的图表,第三个面板中只有Var3的图表。使用以下代码:
library(multipanelfigure)

fig1 <- multi_panel_figure(columns = 2, rows = 2, panel_label_type = "none")

# fit the plots on the panels
fig1 %<>%
  fill_panel(Var1Plot, column = 1, row = 1) %<>%
  fill_panel(Var2Plot, column = 2, row = 1) %<>%
  fill_panel(Var3Plot, column = 1:2, row = 2) 

fig1

问题是如何获取Var1Plot,Var2Plot和Var3Plot,以便将它们放置在相应的面板上方。我使用了以下代码,但无法将结果放置在上述面板中:
 library(tidyverse)
 df %>% ggplot(aes(x = Value, y = n)) +
  geom_bar(stat='identity') + facet_wrap(~ Stat)

期望的图表应该看起来像这样:

enter image description here


从你的问题中不清楚你期望什么输出。这与使用 facet_wrap(~ Stat, nrow = 2, ncol = 2) 有何不同?也许你可以在画图软件或预览中提供一个模拟图? - Ian Campbell
@IanCampbell - 已添加所引用的图表...facet_wrap()不是将图表打印到面板中的函数。我已经尝试过了。 - LeMarque
1个回答

3
这里有一个使用cowplot的方法。
library(cowplot)
figure.list <- map(unique(df$Stat), ~
  ggplot(data = subset(df, df$Stat == .x), aes(x = Value, y = n)) +
  geom_bar(stat='identity') + 
  ggtitle(.x))

top <- plot_grid(figure.list[[1]], figure.list[[2]], ncol = 2)
bottom <- plot_grid(figure.list[[3]], ncol = 1)
plot_grid(top, bottom,
          ncol=1, rel_heights=c(1,1))

这里输入图片描述

如果你真的希望有一些东西被coord_flip翻转,你可以手动创建列表:

figure.list <- list()
figure.list[[1]] <- ggplot(data = subset(df, df$Stat == "Var1"), aes(x = Value, y = n)) +
  geom_bar(stat='identity') + coord_flip()
figure.list[[2]] <- ggplot(data = subset(df, df$Stat == "Var2"), aes(x = Value, y = n)) +
  geom_bar(stat='identity') + coord_flip()
figure.list[[3]] <- ggplot(data = subset(df, df$Stat == "Var3"), aes(x = Value, y = n)) +
  geom_bar(stat='identity')


top <- plot_grid(figure.list[[1]], figure.list[[2]], ncol = 2)
bottom <- plot_grid(figure.list[[3]], ncol = 1)
plot_grid(top, bottom,
          ncol=1, rel_heights=c(1,1))

enter image description here


还有一件事...在这种情况下如何在每个图中获取变量名称? - LeMarque
1
看看我的编辑是否有帮助。我将更新标题,这样其他人就可以找到你的问题了。如果你不喜欢,随时可以改回来。 - Ian Campbell

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接