Home > database >  Add a multi x-axis in each facet wrap
Add a multi x-axis in each facet wrap

Time:06-11

i would like to have a barplot showing a multi level x-axis (YEAR*Quarters) in each panel:

Years <-  c("2016","2016","2016","2016",
           "2017","2017","2017","2017", "2016","2016","2016","2016",
           "2017","2017","2017","2017")
Quarters <-  c("1","2","3","4",
        "1","2","3","4", "1","2","3","4",
        "1","2","3","4")
panel<-  c("A","A","A","A",
        "A","A","A","A", "B","B","B","B",
        "B","B","B","B")
Series1 <- c("100","200","300","400","500","600","700","800", "400","200","300","600","500","300","700","800")

I've tried as follow But i saw in the same x line Quarters and Years

ggplot(aes(x=interaction(Quarters, Years), y=Series))  
    
    geom_bar(stat="identity", 
             position=position_dodge())  facet_wrap(~panel, scales = "free")

CodePudding user response:

This looks like a good use case for nested facets. First put all your variables in a data frame (your code isn't reproducible in its current format)

df <- structure(list(Years = c("2016", "2016", "2016", "2016", "2017", 
"2017", "2017", "2017", "2016", "2016", "2016", "2016", "2017", 
"2017", "2017", "2017"), Quarters = c("1", "2", "3", "4", "1", 
"2", "3", "4", "1", "2", "3", "4", "1", "2", "3", "4"), panel = c("A", 
"A", "A", "A", "A", "A", "A", "A", "B", "B", "B", "B", "B", "B", 
"B", "B"), Series1 = c("100", "200", "300", "400", "500", "600", 
"700", "800", "400", "200", "300", "600", "500", "300", "700", 
"800")), class = "data.frame", row.names = c(NA, -16L))

Now the code for plotting is:

library(ggh4x)

ggplot(df, aes(Quarters, Series1))  
  geom_col()  
  facet_nested(.~ panel   Years)

enter image description here

  • Related