Home > Blockchain >  R: Reorder Top-Down Order of Stacked Bar in Histogram
R: Reorder Top-Down Order of Stacked Bar in Histogram

Time:07-10

I am trying to plot the distance traveled on a histogram and have coloured the distance traveled in three categories (<0km - did not reach destination, =0km did reach destination, and >0km - going farther than destination). In the middle, there is a stacked bar, and what I would like is for the green stacked bar to be at the bottom (closest to the other green bars), the blue bar to be in the middle, and the red bar to be on top.

This is a minimal example of my data, where for Group: -1 means did not reach destination, 0 means reached destination, 1 means going farther than destination.

structure(list(excess_distance_km = c(87.5, 27.8, 18, 22.3, 35, 
120.6, -0.3, 0, 0, 24.6, -0.2, 2.9, 2.9, 8.7, 27.6, 32.9, 32.9, 
0, -0.2, -52.3, 54.4, 64.2, 64.2, 64.2, 50.2, 43.5, -13.5, -17.6, 
82.1, 82.1, 0, 74, 34.9, 35.2, 0, 2, -11.4, 0, 2.5, -52.3, 68.1, 
18, 0, 74.5, 29.6, 0.2, 18.9, 0, 0.7, 1.4), Group = c(" 1", " 1", 
" 1", " 1", " 1", " 1", "-1", "0", "0", " 1", "-1", " 1", " 1", 
" 1", " 1", " 1", " 1", "0", "-1", "-1", " 1", " 1", " 1", " 1", 
" 1", " 1", "-1", "-1", " 1", " 1", "0", " 1", " 1", " 1", "0", 
" 1", "-1", "0", " 1", "-1", " 1", " 1", "0", " 1", " 1", " 1", 
" 1", "0", " 1", " 1")), row.names = c(NA, -50L), class = "data.frame")

Here is my code:

df %>%
  ggplot( aes(x = excess_distance_km))  
    geom_histogram(aes(fill = Group), binwidth=5, alpha=0.9, colour = "grey25")  
    ggtitle("Excess Distance")  
    theme_classic()  
    theme(plot.title = element_text(size=15, hjust = 0.5),
          axis.title = element_text(size=12, hjust = 0.5),
          legend.text = element_text(size=12),
          legend.title = element_blank(),
          legend.position = "bottom"
    )  
  guides(fill = guide_legend(nrow = 3)) 

This is what it looks like right now: enter image description here

CodePudding user response:

You could achieve your desired result by converting Group to a factor with the order of the levels set in your desired order:

library(ggplot2)
library(dplyr, warn=FALSE)

df %>%
  mutate(Group = factor(Group, levels = c("-1", "0", " 1"))) %>%
  ggplot( aes(x = excess_distance_km))  
  geom_histogram(aes(fill = Group), binwidth=5, alpha=0.9, colour = "grey25")  
  ggtitle("Excess Distance")  
  theme_classic()  
  theme(plot.title = element_text(size=15, hjust = 0.5),
        axis.title = element_text(size=12, hjust = 0.5),
        legend.text = element_text(size=12),
        legend.title = element_blank(),
        legend.position = "bottom"
  )  
  guides(fill = guide_legend(nrow = 3)) 

  • Related