我在对某个时间点内不同医疗设备的数据集进行分面处理时遇到问题。我想要做的图使用带有两个变量的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")
我首先尝试将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)
关于r - 切换两个小面条标签的位置并跨列合并一个标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71327369/