2019-10-23

How to reorder bar charts with ggplot2

Problem

We'd like to reorder the bars of a bar chart. In our example below, the bars are not plotted in ascending or descending order.

library(tidyverse)
ggplot(df, aes(x = Position)) + geom_bar()
  • Data frame
  • df <- structure(list(Position = structure(c(3L, 3L, 1L, 1L, 1L, 2L), .Label = c("Defense", 
    "Striker", "Zoalkeeper"), class = "factor"), Name = structure(c(2L, 
    1L, 3L, 5L, 4L, 6L), .Label = c("Frank", "James", "Jean", "John", 
    "Steve", "Tim"), class = "factor")), class = "data.frame", row.names = c(NA, 
    -6L))
    
        Position  Name
    1 Zoalkeeper James
    2 Zoalkeeper Frank
    3    Defense  Jean
    4    Defense Steve
    5    Defense  John
    6    Striker   Tim
    

    Solution

    An alternative is using reorder to order the levels of a factor. In ascending (n) or descending order (-n) based on the count:

    • Descending order
    • df %>%
        count(Position) %>%
        ggplot(aes(x = reorder(Position, -n), y = n)) +
        geom_bar(stat = 'identity') +
        xlab("Position")
      
    • Ascending order
    • df %>%
        count(Position) %>%
        ggplot(aes(x = reorder(Position, n), y = n)) +
        geom_bar(stat = 'identity') +
        xlab("Position")
      

    References

    No hay comentarios:

    Publicar un comentario

    Nube de datos