Reordering factor for plotting using forcats and ggplot2 packages from tidyverse

时间:2017-08-04 12:58:28

标签: r ggplot2 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))

enter image description here

Bar chart enter image description here

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?

2 个答案:

答案 0 :(得分:1)

uniqueggplot (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))) 级别一起用于x轴。

{{1}}

编辑:@dotorate评论

答案 1 :(得分:0)

在奖金

之前排除failNo
library(dplyr)
df_before_bonus <- df %>% filter(Bonus == "Before") %>% arrange(desc(FailNo))

在奖金之前使用FailNo来创建因子

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

更新的情节

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

enter image description here