Home > front end >  Reordering bars in combined dodged and stacked graph
Reordering bars in combined dodged and stacked graph

Time:04-14

I am trying to re-order the bars on this graph. Graphing across time, with two main groups displayed on the x axis (G1 & G2). The stacks are set on Group.2, which is a yes/no. Within group G2, there are subgroups. How do I re-order the subgroups within G2 such that the light blue ('No' within Group.2 and 'GY' within Group.4) occurs directly above the dark blue ('Yes' for Group.2 and 'GY' for Group.4), and the same with the green bars in G2? Ultimately, I want the groups of G2 to be dark green on bottom, then light green, then dark blue, then light blue.

ag <- data.frame("Group.1" = c("Jan", "Feb", "Jan", "Feb",
                               "Jan", "Feb", "Jan", "Feb",
                               "Jan", "Feb", "Jan", "Feb"),
                 "x" = c(10000, 7000, 3000, 2000, 5000, 4000, 2000, 1800,
                         3000, 2500, 1800, 1500),
                 "Group.2" = c("Yes", "Yes", "No", "No", "Yes", "Yes", "No", "No",
                               "Yes", "Yes", "No", "No"),
                 "Group.3" = c("G1", "G1", "G1", "G1", "G2", "G2", "G2", "G2",
                               "G2", "G2", "G2", "G2"),
                 "Group.4" = c("G1", "G1", "G1", "G1", "GX", "GX", "GX", "GX",
                               "GY", "GY", "GY", "GY"))
ag$Group.1 <- factor(ag$Group.1, levels = c("Jan", "Feb"))
ag$lbl <- ag$x
ggplot(ag, 
       aes(x = Group.3, y = x, alpha = Group.2, fill = Group.4))  
  geom_col(position = position_stack(), colour = "black")  
  geom_text(position = position_stack(vjust = .5), 
            aes(label = lbl), alpha = 1)  
  facet_grid(~Group.1)  
  scale_fill_manual(values = c("red", "green", "blue")) 

enter image description here

CodePudding user response:

You could achieve your desired result by mapping Group.4 on the group aesthetic so that the bars get grouped by Group.4. I also switched the blue and green colors in your palette so that the bars at the bottom get colored green.

library(ggplot2)

ggplot(
  ag,
  aes(x = Group.3, y = x, alpha = Group.2, fill = Group.4, group = Group.4)
)  
  geom_col(position = position_stack(), colour = "black")  
  geom_text(
    position = position_stack(vjust = .5),
    aes(label = lbl), alpha = 1
  )  
  facet_grid(~Group.1)  
  scale_fill_manual(values = c("red", "blue", "green"))
#> Warning: Using alpha for a discrete variable is not advised.

  • Related