M.R.Wani
M.R.Wani

Reputation: 107

How to reorder the levels of a factor in increasing or decreasing order?

my_file <- read.csv("https://github.com/rfordatascience/tidytuesday/blob/master/data/2018-10-16/recent-grads.csv")

I use this code:

my_file %>% 
  mutate(Major_category = fct_reorder(Major_category,Unemployed)) %>%       
  ggplot(aes(x= Major_category,y= Unemployed, fill = Major_category)) + 
  geom_bar(stat = "identity") + 
  theme_minimal() + 
  labs(title = "Unemployed Students in Various Majors", x ="Major") + 
  theme(legend.position = "none", 
        plot.title = element_text(hjust = 0.5)) +
  coord_flip()

Even after using reorder(), the levels are not reordered? Please helpenter image description here

Upvotes: 0

Views: 1039

Answers (1)

Stephan
Stephan

Reputation: 2246

you need to summarise the categories first:

 library(tidyverse)
 my_file <- read_csv("https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2018-10-16/recent-grads.csv")

 my_file %>% 

   # summarise categories
   group_by(Major_category) %>% 
   summarise(Unemployed = sum(Unemployed, na.rm = TRUE)) %>% 

   #now use your code
   mutate(Major_category = fct_reorder(Major_category, Unemployed)) %>%
   ggplot(aes(x = Major_category, 
              y = Unemployed, 
              fill = Major_category)) + 
   geom_bar(stat = "identity") + 
   theme_minimal() + 
   labs(title = "Unemployed Students in Various Majors", x ="Major") + 
   theme(legend.position = "none", 
         plot.title = element_text(hjust = 0.5)) +
   coord_flip()

output is: enter image description here

Upvotes: 3

Related Questions