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

问题描述 投票:0回答:1

我正在尝试绘制个人在许多任务上的表现。绩效按类别进行评分,我想以堆叠的条形图显示每个人的整体绩效,其中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")

这是数字:

enter image description here

这几乎是我想要的,除了CAT对负值的排序相反,并且我也希望条形也根据因子水平和负值的填充图例进行堆叠,即:Poor> Failing> Missing。这肯定在以前出现过,但是我在这里或其他地方找不到解决方案。预先感谢!

r ggplot2 bar-chart r-factor
1个回答
1
投票

[enter image description here使用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")

© www.soinside.com 2019 - 2024. All rights reserved.