Jordan_b
Jordan_b

Reputation: 315

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 )

Upvotes: 3

Views: 179

Answers (2)

s__
s__

Reputation: 9485

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

Upvotes: 3

Georgery
Georgery

Reputation: 8117

This should do it.

df %>% # take the dataframe and then...
    group_by(ct) %>% # per group...
    mutate(order = sum(value * (var == "first"))) %>% # you calculate the sum of value where var is "first"
    ggplot(aes(reorder(ct, order) # ...and then plot everything.
               , value
               , fill = var)) +
    geom_bar(stat = "identity"
             , position = "dodge"
             , width = .9)

enter image description here

Upvotes: 1

Related Questions