Mostrando entradas con la etiqueta xlab. Mostrar todas las entradas
Mostrando entradas con la etiqueta xlab. Mostrar todas las entradas

2019-11-01

Cómo reordenar diagramas de barras en ggplot2

Problema

Queremos reodernar las barras de un diagrama de barras creado con ggplot2. En nuestro ejemplo, se puede observar que las barras no están ni en orden ascendente o descendente.

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
    

    Solución

    Una alternativa es usar reorder para reordenar los niveles del factor. En orden ascendente (n) o descendente (-n) en función del conteo de la columna Position.

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

    Entradas relacionadas

    Referencias

    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

    Nube de datos