简体   繁体   中英

Reordering factor for plotting using forcats and ggplot2 packages from tidyverse

First of all, thanks ^13 to tidyverse . I want the bars in the chart below to follow the same factor levels reordered by forcats::fct_reorder () . Surprisingly, I see different order of levels in the data set when View () ed as when they are displayed in the chart (see below). The chart should illustrate the number of failed students before and after the bonus marks (I want to sort the bars based on the number of failed students before the bonus).

MWE

  ggplot (df) +
  geom_bar (aes (forcats::fct_reorder (subject, FailNo, .desc= TRUE), FailNo, fill = forcats::fct_rev (Bonus)), position = 'dodge', stat = 'identity') +
  theme (axis.text.x=element_text(angle=45, vjust=1.5, hjust=1.5, size = rel (1.2)))

Data output of dput (df)

structure(list(subject = structure(c(1L, 2L, 5L, 6L, 3L, 7L,
4L, 9L, 10L, 8L, 12L, 11L, 1L, 2L, 5L, 6L, 3L, 7L, 4L, 9L, 10L,
8L, 12L, 11L), .Label = c("CAB_1", "DEM_1", "SSR_2", "RRG_1",
"TTP_1", "TTP_2", "IMM_1", "RRG_2", "DEM_2", "VRR_2", "PRS_2",
"COM_2", "MEB_2", "PHH_1", "PHH_2"), class = "factor"), Bonus = structure(c(2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("After", "Before"), class = "factor"),
    FailNo = c(29, 28, 20, 18, 15, 13, 12, 8, 5, 4, 4, 2, 21,
    16, 16, 14, 7, 10, 10, 5, 3, 4, 4, 1)), .Names = c("subject",
"Bonus", "FailNo"), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-24L))

在此处输入图片说明

Bar chart 在此处输入图片说明

The issue

According to the table above, SSR_2 var should come in the fifth rank and IMM_1 in the sixth, however in the chart we see these two variables swapping their positions. How to sort it right after tidyverse in this case?

Use factor with unique levels for your x -axis.

ggplot (df) + 
 geom_bar (aes(factor(forcats::fct_reorder
 (subject, FailNo, .desc= TRUE), 
 levels=unique(subject)), 
 FailNo, 
 fill = forcats::fct_rev (Bonus)), 
 position = 'dodge', stat = 'identity') + 
 theme(axis.text.x=element_text(angle=45, vjust=1.5, hjust=1.5, size = rel (1.2)))

Edited: @dotorate comment

Sort failNo before the bonus

library(dplyr)
df_before_bonus <- df %>% filter(Bonus == "Before") %>% arrange(desc(FailNo))

Use FailNo before the bonus to create the factor

df$subject <- factor(df$subject, levels = df_before_bonus$subject, ordered = TRUE)

Updated plot

ggplot(df) +
    geom_bar(aes (x = subject, y = FailNo, fill = as.factor(Bonus)), 
             position = 'dodge', stat = 'identity') +
    theme (axis.text.x=element_text(angle=45, vjust=1.5, hjust=1.5, size = rel (1.2)))

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM