Search code examples
rsortingggplot2geom-bar

How to sort the double bar using ggplot in r?


I am learning r and I have problem with sorting the double bar in ascending or descending order and I want to set the legend just on the top of the plot with two color represent respectively with one row and two columns like for example:

The title Time

box color Breakfast box color Dinner

And the plot here

Here is my dataframe:

dat <- data.frame(
  time = factor(c("Breakfast","Breakfast","Breakfast","Breakfast","Breakfast","Lunch","Lunch","Lunch","Lunch","Lunch","Lunch","Dinner","Dinner","Dinner","Dinner","Dinner","Dinner","Dinner"), levels=c("Breakfast","Lunch","Dinner")),
  class = c("a","a","b","b","c","a","b","b","c","c","c","a","a","b","b","b","c","c"))

And here is my code to make change:

dat %>% 
  filter(time %in% c("Breakfast", "Dinner")) %>%
  droplevels %>%
  count(time, class) %>% 
  group_by(time) %>% 
  mutate(prop = n/sum(n)) %>%
  ggplot(aes(x = class, y = prop, fill = time, label = scales::percent(prop))) +
  geom_col(position = 'dodge') +
  geom_text(position = position_dodge(width = 0.9), vjust = 0.5, size = 3) + 
  scale_y_continuous(labels = scales::percent)+
  coord_flip()

Any help would be appreciated.


Solution

  • To get the legend title above the legend key, requires a little additional adjustments to the theme and guides.

    dat %>% 
      filter(time %in% c("Breakfast", "Dinner")) %>%
      droplevels %>%
      count(time, class) %>% 
      group_by(time) %>% 
      mutate(prop = n/sum(n)) %>%
      ggplot(aes(x = class, y = prop, fill = time, label = scales::percent(prop))) +
      geom_col(position = 'dodge') +
      geom_text(position = position_dodge(width = 0.9), vjust = 0.5, size = 3) + 
      scale_y_continuous(labels = scales::percent)+
      coord_flip() +
      theme(legend.position="top", legend.direction="vertical", legend.title=element_text(hjust = 0.5))+
      guides(fill = guide_legend(title = "Time", nrow = 1))
    

    enter image description here