rggplot2waffle

How to choose the levels order of the fill variable with waffle::geom_waffle()


I don't understand how I can change the levels order of the fill variable in R waffle::geom_waffle().

It seems that sorting the variable is ineffective since it's always sorted by the number of observations.

# First example
db_graph <- data.table::data.table(group = c("A", "B"),
                                   n     = c(13, 25))

ggplot2::ggplot(data    = db_graph,
                mapping = ggplot2::aes(fill   = group,
                                       values = n)) +
  waffle::geom_waffle(flip = TRUE)

# Second example
db_graph <- db_graph[j = group := forcats::fct_rev(group)]

ggplot2::ggplot(data    = db_graph,
                mapping = ggplot2::aes(fill   = group,
                                       values = n)) +
  waffle::geom_waffle(flip = TRUE)

Solution

  • You could achieve your desired result by reordering your dataframe using e.g. setorder(db_graph, group). But you are right. I would have expected too that the order is determined by the order of the factor levels.

    library(ggplot2)
    library(data.table)
    library(waffle)
    library(forcats)
    
    db_graph <- data.table::data.table(
      group = c("A", "B"),
      n = c(13, 25)
    )
    
    db_graph <- db_graph[j = group := fct_rev(group)]
    
    ggplot(
      data = db_graph,
      mapping = aes(
        fill = group,
        values = n
      )
    ) +
      geom_waffle(flip = TRUE) 
    

    setorder(db_graph, group)
    
    ggplot(
      data = db_graph,
      mapping = aes(
        fill = group,
        values = n
      )
    ) +
      geom_waffle(flip = TRUE)