r - 切换两个小面条标签的位置并跨列合并一个标签

标签 r ggplot2 facet strip facet-wrap

我在对某个时间点内不同医疗设备的数据集进行分面处理时遇到问题。我想要做的图使用带有两个变量的facet_wrap(我知道我也可以使用facet_grid,但更喜欢在这个图中facet_wrap的外观案例)

我遇到的问题是: 1.) strip 标签的方向,我希望顶部 strip 位于另一个 strip 下方,并且 2)我希望底部 strip 标签能够跨越两列,因为它是相同的。

示例数据集和代码如下:

library(tidyverse)
library(ggplot2)

dt <- tibble(device_type = c("Stent","Stent","Stent","Stent", "Pace","Pace","Pace","Pace"),
             days = c(5,10,15,2,4,6,6,8),
             generation = c("First", "Second","First", "Second","First", "Second","First", "Second"),
             year = c("Before", "Before","After", "After","Before", "Before","After", "After"))


dt %>% 
  ggplot(aes(x=generation, y= days))+
    geom_bar(stat = "identity")+
    facet_wrap(~device_type + year, strip.position = "bottom", nrow = 1)+
    theme(strip.placement = "outside")

给出了情节:plot

我试图让小面条标签的方向看起来像这样: desired plot

我首先尝试将facet_wrap行中变量的位置更改为facet_wrap(~year + device_type, strip.position = "bottom", nrow = 1)但这会改变这样的情节它将分组分成年份的方式对于我使用它的实际数据集来说并不理想。

我找到了这篇文章Combine multiple facet strips across columns in ggplot2 facet_wrap利用facet_nested,但无法使其与 strip 标签的切换一起使用。任何帮助或想法将不胜感激。

最佳答案

这可以通过 teunbrand 编写的 ggh4x 包轻松完成: 使用facet_nested_wrap函数: 您可以更改要组合的内容,只需更改 facet_nested_wrap 中的顺序即可:

library(tidyverse)
#install.packages("ggh4x")
library(ggh4x)

dt %>% 
  ggplot(aes(x=generation, y= days))+
  geom_bar(stat = "identity")+
  facet_nested_wrap(~year + device_type, nrow = 1, ncol=4)

enter image description here

关于r - 切换两个小面条标签的位置并跨列合并一个标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71327369/

相关文章:

r - 尝试不使用merge()和使用union(),match()或%in%合并两个数据帧

r - 在r中的某个阈值处破坏 cumsum() 函数

r - 将第 N 行的 NA 行插入到列表中的数据帧列表中,其中 N 来自列表

r - ggplot2中的比例图图例显示

r - 如何更改ggplot2中的默认配色方案?

r - ggplot2 : scales that are "free and equal"? 中的多面板图

facet - Algolia facet 按空/空值过滤

在 R 中读取 CSV 文件并格式化日期和时间,同时读取并避免标记为的缺失值?

java - 如何指定多个 Spring Data Solr Facet 字段?

C++ boost 日期格式