繁体   English   中英

修复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()

并得到这个:

在此处输入图片说明

问题在于,覆盖层“隐藏”了较低层。 理想情况下,我希望每个部分都定义清楚,并用黑色轮廓标出。 我真的不明白,这困扰着我。 我正在尝试重新创建如下内容:

在此处输入图片说明

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

对此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')

在此处输入图片说明

UPDATE

您的重叠式广告无法完美运行,因为您有重复的Notification值。 参见下文-首先通过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)))

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM