Search code examples
rggplot2facet-wrap

Arranging factors in increasing order


I am trying to create two plots which should display frequency in a decreasing order.

#preparing the data to resemble actual data
test <- data.frame(HairEyeColor) %>%
  mutate(combi = paste(Hair,Eye)) %>%
  group_by(Sex) %>%
  mutate(prop = Freq / sum(Freq))  %>%
  ungroup() 
test$combi <- factor(test$combi)
freq_test_count <- test %>%
  setorder(Freq)

#creating the plot
freq_test_plot <- freq_test_count %>%
  ggplot(aes(x = reorder(combi,prop),y = prop, label = Freq)) +
  geom_col(show.legend = FALSE) +
  geom_text(check_overlap = TRUE, nudge_y = 0.005, size = 3) + 
  facet_wrap(~Sex, scales = "free") +
  labs(y = "Proportion",
       x = NULL) +
  coord_flip()

When i plot freq_test_plot, it shows the plot but the output is not in decreasing order

I am not sure what should I do so that I can see terms in decreasing order of frequency.

enter image description here


Solution

  • A workaround is to create two different plots and arrange them in grid. But you should be cautious because, like Gregor mentioned, it could definitely be misleading.

    library(grid)
    p1 = freq_test_count[freq_test_count$Sex == "Male",] %>%
        ggplot(aes(x = reorder(combi,prop),y = prop, label = Freq)) +
        geom_col(show.legend = FALSE) +
        geom_text(check_overlap = TRUE, nudge_y = 0.005, size = 3) + 
        facet_wrap(~Sex, scales = "free") +
        labs(y = "Proportion",
             x = NULL) +
        coord_flip()
    
    p2 = freq_test_count[freq_test_count$Sex == "Female",] %>%
        ggplot(aes(x = reorder(combi,prop),y = prop, label = Freq)) +
        geom_col(show.legend = FALSE) +
        geom_text(check_overlap = TRUE, nudge_y = 0.005, size = 3) + 
        facet_wrap(~Sex, scales = "free") +
        labs(y = "Proportion",
             x = NULL) +
        coord_flip()
    
    graphics.off()
    grid.newpage()
    grid.draw(ggarrange(p1, p2, ncol = 2))
    

    enter image description here