lasagna
lasagna

Reputation: 174

Reordering x axes on ggplot

Im trying to do a demographic pyramid, but when I do the ggplot, the groups reorder in a different way, for example the 5 to 9 old go way up, as you can see in the following example.

demo=demo %>% arrange(factor(Grupos, levels = c('0-4 años', '5-9 años', '10-14 años', '15-19 años', '20-24 años', '25-29 años', '30-34 años','35-39 años','40-44 años','45-49 años','50-54 años','55-59 años','60-64 años','65-69 años','70-74 años','75-79 años','80-84 años','85+')))


library(ggplot2)
library(lemon)

popchart=ggplot(demo, aes(x = Grupos, y = Valor, fill = Grupo)) + 
  geom_bar(data = subset(demo, Grupo == "Mujer"), stat = "identity") +
  geom_bar(data = subset(demo, Grupo == "Hombre"), stat = "identity") + 
  scale_y_symmetric(labels = abs) +
  coord_flip()

Giving to me the following output

Graph1

And idea how to fix it?

Upvotes: 0

Views: 51

Answers (1)

Ben Bolker
Ben Bolker

Reputation: 226047

ggplot orders variables according to factor levels, not according to the order of rows in the data set. Your code hasn't actually saved the factor level-ordering of Grupos. You should probably use mutate to do this. I'm going to give a slightly abbreviated version because I don't have your data set and I'm lazy. Suppose the levels in your Grupos variable are "0 a 4", "5 a 9", "10 a 14", "15+".

level_vec <- c("0 a 4", "5 a 9", "10 a 14", "15+")
label_vec <- c('0-4 años', '5-9 años', '10-14 años', '15+ años')
demo <- demo %>% 
    mutate(across(Grupos, factor, levels = level_vec, labels = label_vec))

Provided that your levels are in order in the original data set, you could probably also use mutate(across(Grupos, forcats::fct_inorder)); that won't get you the nice labels, but it will save you writing out the levels vector.

Upvotes: 1

Related Questions