I am having an issue with faceting a dataset looking at different medical devices over a certain time point. The figure I am looking to do uses a facet_wrap
with two variables (I know I could also use facet_grid
but prefer the appearance of facet_wrap
in this case)
The issue I have is: 1.) The orientation of the strip labels, where I would like the top strip to be below the other one and 2) that I would like the bottom strip label to cross both columns as it is the same.
An example dataset and code is below:
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")
What I am trying to get the orientation of the facet strip labels to look like is here:
I first tried changing the position of the variables in the facet_wrap line to facet_wrap(~year + device_type, strip.position = "bottom", nrow = 1)
but this alters the plot in such a way that it splits the grouping into years which is not ideal for the actual dataset im using this on.
I found this post Combine multiple facet strips across columns in ggplot2 facet_wrap utilizing facet_nested
but have been unable to get this to work with the switching of the strip labels. Any help or ideas would be greatly appreciated.
This could be easily done with ggh4x
package written by teunbrand:
Using facet_nested_wrap
function:
You can change which one you want to combine, just change the order in 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)