修复 ggplot 中叠加 geom_bar 和 position_identity() 的顺序

Fix the ordering of overlaid geom_bar and position_identity() in ggplot

有几个问题询问 堆叠 geom_bar() 图的排序。然而,我有一个问题,我需要覆盖条形图,但由于某种原因,排序使得底层被最顶层隐藏。考虑这个例子:

df_example = data.frame(Month = rep(c(1:8),2),
                    Type = c(rep("Email",8),rep("SMS",8)),
                    Notifications = c(4,7,9,11,13,17,19,20,2,4,4,3,3,3,4,4))

然后我使用 ggplot2 和 geom_bar()

绘图
ggplot(data=df_example,aes(x=Type, y=Notifications, fill=Type, color=Type))+
geom_bar(stat="identity",position ="identity", color= "black",alpha=0.5)+
coord_flip()

得到这个:

问题是叠加层是 "hiding" 下层。理想情况下,我希望每个部分都定义明确,并用黑色轮廓标定。我真的无法理解,这让我很烦。我正在尝试重新创建这样的东西:

请注意,这是在油漆中完成的,因此数字不会对齐 - 但视觉创意就在那里。

对于这个 ggplot 问题的任何帮助将不胜感激。

您可以试试这个:添加行号,按类型分组,然后用它来填充每种颜色并堆叠条形。然后您可以编辑颜色并删除图例。

df %>% group_by(Type) %>% mutate(r=factor(seq(1,n()))) %>% 
  ggplot(aes(x=Type, y=Notifications))+
  geom_bar(aes(fill=r),stat="identity",position = 'stack', color= "black") +
  scale_fill_manual(values=c(rep('lightblue',8))) +
  theme(legend.position = 'none')

更新

您的覆盖想法不会完美地工作,因为您有重复的通知值。见下文——首先通过 Notification 排列数据,然后绘图实现纯色覆盖,但隐藏了存在重复的事实(而堆积条显示了这一点)。

df %>% arrange(Type,-Notifications) %>% 
  ggplot(.,aes(x=Type, y=Notifications))+
  geom_bar(aes(fill='Type'),stat="identity",position ="identity", color= "black") +
  scale_fill_manual(values=c(rep('lightblue',16)))