F.Gr. F.Gr. - 3 months ago 8
R Question

R ggplot // Multiple Grouping in X-axis

I am trying to implement the diagram 1 from Excel to Shiny. So far I got this code with the resulting diagram 2.

ggplot(filteredData(), aes(x=interaction(month, year), y=sum))
+ geom_bar(stat="identity") + facet_grid(. ~ X) + theme(legend.position="none")


I want to group month and year like in the Excel example, so hat you have only the month counter ("1", "2", ...) in the first row of the legend and the year ("2016", "2017", ...) in the second. The number of months can vary.

The data set looks like:

X year month sum
10 2016 1 450
10 2016 2 670
... ... ... ...
10 2017 1 200
11 2016 1 460

Answer

I slightly changed the data set, this is the closest I got to your specs:

df <- read.table(text = "X    year  month  sum
10   2016  1      450
10   2016  2      670
10   2017  1      200
11   2016  1      460
11   2017  2      500", header = T)

# Notice the variable type for month and year
df$month <- as.factor(df$month)
df$year <- as.factor(df$year)
df$X <- as.factor(df$X)

 ggplot(df, aes(x = month, y = sum)) + geom_bar(stat = "identity") + 
  facet_grid(.~X + year,
             switch = "x", # Moves the labels from the top to the bottom
             labeller = label_both # Adds the labels to the year and X variables
             ) + 
  xlab("") # Removes the month label

Result: enter image description here

Or if you want to drop unused levels:

ggplot(df, aes(x = month, y = sum)) + geom_bar(stat = "identity") + 
  facet_grid(.~X + year,
             switch = "x", # Moves the labels from the top to the bottom
             labeller = label_both, # Adds the labels to the year and X variables
             scales = "free_x") + 
  xlab("") # Removes the month legend

enter image description here