为什么堆积条形图中的负值的填充顺序相反? (R,ggplot2)

Why does the fill order reverse for negative values in stacked bar charts? (R, ggplot2)

我正在尝试绘制个人在多项任务上的表现。性能按类别进行评级,我想将每个人的整体性能显示为堆叠条形图,其中 Y 代表每个性能类别中答案的百分比,正值表示良好,负值表示性能差或缺失答案。这是一个玩具数据集和我设法制作的当前情节:

df <- data.frame(SRC = rep(LETTERS[1:14],each=6),
                 CAT = rep(c("Excellent","VeryGood","Good","Poor","Failing","Missing"),times=14),
                 PERCENT = c(29.3, 23.3, 30, -13.3, -4, 0, 16.7, 15.3, 38.7, -14.7, -4.7, 
                             -10, 12, 9.3, 30.7, -19.3, -19.3, -9.3, 2.7, 6.7, 20, -23.3, 
                             -14, -33.3, 16, 23.3, 20.7, -10.7, -9.3, -20, 24.7, 22, 12.7, 
                             -8, -2, -30.7, 14, 15.3, 23.3, -4, -4.7, -38.7, 4.7, 6, 60, -24, 
                             -4.7, -0.7, 8, 13.3, 57.3, -16, -3.3, -2, 8, 11.3, 62, -12.7, 
                             -5.3, -0.7, 9.3, 14.7, 64.7, -10, -1.3, 0, 20.1, 20.9, 32.5, 
                             -1.5, 0, 0, 14.2, 10.4, 33.2, -6.6, -2.8, 0, 14.7, 18.7, 55.3, 
                             -10.7, 0, -0.7))

df$CAT <- ordered(df$CAT,levels=c("Excellent","VeryGood","Good","Poor","Failing","Missing"))

ggplot(df, aes(x=SRC, y=PERCENT, fill=CAT,group=CAT,group=SRC)) + 
  geom_bar(position="stack", stat="identity")

这是图:

这几乎是我想要的,除了 CAT 对于负值是反向排序的,我希望条形图根据因子水平和负值的填充图例堆叠 ,即 Poor>Failing>Missing。这肯定是以前出现过的,但我无法在这里或其他地方找到解决方案。提前致谢!

使用 forecats 库:

library(forecats)



df %>% 
mutate(CAT=fct_relevel(CAT,"Excellent","VeryGood","Good","Missing","Failing","Poor")) %>% 
ggplot( aes(x=SRC, y=PERCENT, fill=CAT)) + 
  geom_bar(position="stack", stat="identity")