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

Time:11-19

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?

CodePudding user response:

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 enter image description here

The order is not ascending. However if you use mutate in conjunction with fct_reorder, and reorder "streaming" according to "media_IMDB" :

descritivasseries %>% mutate(streaming = fct_reorder(streaming, media_IMDB, .desc=FALSE))  %>%
ggplot()   geom_col(aes(x = streaming, y = media_IMDB),
                  fill = "seagreen1")  
labs(title = "Avaliação das Séries",
   x = "", y = "Média das Notas IMDb")

enter image description here

  • Related