Search code examples
rggplot2geom-bar

R order geom_bar based on one level


How can I order the bar plot based on the first level of the variable var? Now the order is on the sum of the two bars I would like to have it ordered only by value where var is "first". Below a working example.

library("ggplot2")
ct <- rep(c("A", "B", "C", "D"),  2)
var <- c("first","first","first","first","second","second","second","second")
value <- c(1,5,0.5,8,2,11,0.2,0.1)

df <- data.frame(ct, var, value)
df

ggplot() +
  geom_bar(data = df
           , aes(x = reorder(ct, value)
                 , y = value
                 , fill = var
           )
           , stat = "identity"
           , position = "dodge"
           , width = .90 )

Solution

  • With forcats::fct_reorder2() you do not need to modify your data.frame:

    library(ggplot2)
    library(forcats)
    
    ggplot() +
      geom_bar(data = df
               , aes(x = forcats::fct_reorder2(ct, var=='first', value, .desc = F)
                     , y = value
                     , fill = var
               )
               , stat = "identity"
               , position = "dodge"
               , width = .90 ) + labs(x = "ct")
    

    enter image description here