Bar chart sorted using dplyr and ggplot2

5

I'd like to create a bar chart after counting the number of occurrences of categories in a dataset. Suppose my dataset is this below:

dados <- structure(list(categorias = structure(c(5L, 4L, 5L, 3L, 1L, 2L, 
5L, 3L, 1L, 1L, 4L, 4L, 1L, 5L, 3L, 1L, 1L, 1L, 2L, 5L), .Label = c("A", 
"B", "C", "D", "E"), class = "factor")), .Names = "categorias", row.names = c(NA, 
-20L), class = "data.frame")

I can count the number of occurrences of each category and make the corresponding bar chart like this:

dados %>%
  group_by(categorias) %>%
  count() %>%
  ggplot(., aes(x=categorias, y=n)) +
  geom_bar(stat="identity")

However,thebarsareplacedalphabetically.Iwishtheywereplacedfromthemorefrequenttothelessfrequent.Inthecaseofthisexample,theyshouldbeintheorderA,E,C,D,B.

Idonotlikesolutionsusingsomethingontheline

ggplot(dados,aes(x=categorias))+geom_bar(stat="count")

I think my code gets more organized the other way.

Is there any way to do what I want using the first code I put up?

    
asked by anonymous 28.06.2017 / 18:46

1 answer

4

I had an idea how to search my question and I ended up getting an answer a few moments after posting my question:

dados %>%
  group_by(categorias) %>%
  count() %>%
  ggplot(., aes(x=reorder(categorias, -n), y=n)) +
  geom_bar(stat="identity")

    
28.06.2017 / 18:49