如何按升序或降序重新排列因子的水平?

时间:2018-10-16 06:51:14

标签: r ggplot2

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

我使用以下代码:

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()

使用reorder()之后,是否不重新排列级别?请帮助enter image description here

1 个答案:

答案 0 :(得分:3)

您需要先summarise个类别:

 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()

输出为: enter image description here