0

I would like the X axis of a plot to reflect on two groupings, one nested within the other. Take this code for instance:

library(ggplot2)
df <- data.frame(
  year = c(rep('2017', 4), rep('2018', 4)),
  group = rep(c('G1', 'G2', 'G3', 'G4'), 2),
  value = c(10, 11, 14, 13, 17, 15, 19, 21)
)
ggplot(df, aes(interaction(group, year), value)) +
  geom_point() +
  xlab('Time') + ylab('Some value') + theme_bw()

The output is like this:

Output of the code

The desired output, however, is more like this mock-up:

enter image description here

Even better would be if there would be a space between the G4 value and the next G1 value to make the subgroups more distinctive from one another.

Is this even possible with ggplot2?

NOTE that I do not mean a facet because that breaks the X axis into multiple parts. I want to keep the continuity of X axis. Think of G1 - G4 being the quarters of a year.

Merik
  • 2,767
  • 6
  • 25
  • 41
  • 5
    Facet on `year`: `ggplot(df, aes(group, value)) + geom_point() + xlab('Time') + ylab('Some value') + theme_bw() + facet_grid(. ~ year, switch="x") + theme(strip.placement="outside", strip.background=element_rect(colour=NA, fill=NA)) – eipi10 Apr 30 '18 at 18:55
  • Thanks, but the facet feature breaks the plot into multiple sub-plots which means the X axis will be broken, and I would like to avoid that to maintain continuity – Merik Apr 30 '18 at 19:31
  • See the linked answer for how to remove the space between panels. – eipi10 Apr 30 '18 at 19:39

0 Answers0