Search code examples
rggplot2plotdata-visualizationgeom-col

How can I sort my y result when using geom_col()?


I have two plots:

1.

ggplot() + geom_col(data = descritivasseries,
                    aes(x = streaming, y = media_IMDB),
                    fill = "seagreen1") + 
  coord_cartesian(ylim = c(6.85, 7.20)) +
  labs(title = "Avaliação das Séries",
       x = "", y = "Média das Notas IMDb")
ggplot() + geom_col(data = descritivasfilmes,
                    aes(x = streaming, y = media_IMDB),
                    fill  = "deepskyblue") +
  labs(title = "Avaliação dos Filmes", x = "", y = "Média das Notas IMDb") +
  coord_cartesian(ylim = c(5.85, 6.6))

The first one looks like this:

enter image description here

And the second one looks like this:

enter image description here

I would like both of their y results to be organized in ascending order. How would I do that?


Solution

  • You can reorder factors within a ggplot() command using fct_reorder() from the forcats package.

    library(ggplot2)
    library(forcats)
    
    df <- data.frame(
      streaming = c("Disney", "Hulu", "Netflix", "Prime Video"), 
      score = c(4, 2, 3, 1)
    )
    
    # no forcats::fct_reorder()
    ggplot(df, aes(x = streaming, y = score)) +
             geom_col()
    

    # with forcats::fct_reorder()
    ggplot(df, aes(x = forcats::fct_reorder(streaming, score), y = score)) +
             geom_col()
    

    Created on 2021-11-18 by the reprex package (v2.0.1)

    To reverse the order, run

    ggplot(df, aes(x = forcats::fct_reorder(streaming, desc(score)), y = score)) +
             geom_col()