1

我有这个df,

    df <- structure(list(Gender = structure(c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 
3L, 3L, 3L, 3L, 3L, 3L, 3L), .Label = c("", "Female", "Male", 
"Q6 - OBS: Sex of Respondent"), class = "factor"), Incident = c("Death", 
"Detention", "Extortion", "Kidnapping", "Physical_abuse", "Robbery", 
"Sexual_assault", "Death", "Detention", "Extortion", "Kidnapping", 
"Physical_abuse", "Robbery", "Sexual_assault"), Victim = structure(c(5L, 
5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L), .Label = c("", 
"No", "Q54 - Did you   witness any migrant deaths   during your journey?", 
"Refused", "Yes", "Q69 - Did you   experience any physical abuse or harassment (of a non-sexual nature) during your journey?", 
"Q62 - Did you   witness or experience any sexual assault or harassment during your journey?", 
"Q75 - Have   you been kidnapped or otherwise held against your will during your journey?", 
"Q96 - Have you been detained by the police, military, militia or immigration officials during your journey?", 
"Q84 - Have   you ever been robbed during   your journey?", "Q90 - Did you   have to give government officials gifts, services or   bribes during your journey?"
), class = "factor"), n = c(253L, 300L, 1978L, 73L, 740L, 646L, 
553L, 436L, 816L, 4052L, 194L, 1196L, 1059L, 259L), Percent = c(8, 
10, 65, 2, 24, 21, 18, 6, 12, 59, 3, 17, 15, 4)), class = c("grouped_df", 
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -14L), groups = structure(list(
    Gender = structure(c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 
    3L, 3L, 3L, 3L, 3L), .Label = c("", "Female", "Male", "Q6 - OBS: Sex of Respondent"
    ), class = "factor"), Incident = c("Death", "Detention", 
    "Extortion", "Kidnapping", "Physical_abuse", "Robbery", "Sexual_assault", 
    "Death", "Detention", "Extortion", "Kidnapping", "Physical_abuse", 
    "Robbery", "Sexual_assault"), .rows = list(1L, 2L, 3L, 4L, 
        5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L)), row.names = c(NA, 
-14L), class = c("tbl_df", "tbl", "data.frame"), .drop = TRUE))

我这样绘制:

df %>% 
 ggplot(aes(x=Incident, y=Percent, fill=Gender))+
 geom_col(position = "dodge", width=0.72)

现在我需要将事件从较高的总百分比排序到较低的总百分比,以便勒索首先出现在左侧,然后是身体虐待等。我尝试过:

df %>% 
  mutate(Incident=reorder(Incident, -Percent)) %>%
  ggplot(aes(x=Incident, y=Percent, fill=Gender))+
  geom_col(position = "dodge", width=0.72)

但我得到了错误:

Error: Column `Incident` can't be modified because it's a grouping variable

然后我尝试了ungroup,或fct_rev,但我无法让它工作!唯一可行的是将df导出为csv,然后再次导入,然后它就可以工作了。但是,这当然不是很有效......任何人请帮忙!

4

0 回答 0