Luca Pontiggia
Luca Pontiggia

Reputation: 187

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

There are a few questions asking about ordering of stacked geom_bar() graphs. I however have the issue that I need to overlay the bar graphs, but for some reason the ordering is making it so that the bottom layers are getting hidden by the top-most one. Consider this example:

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))

I then plot using ggplot2 and 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()

And get this:

enter image description here

The problem is that the overlaying is "hiding" the lower layers. I ideally want each segment well defined, and demarcated with the black outline. I really can't get this and it's bugging me. I am trying to re-create something like this:

enter image description here

Note, this was done in paint, so the numbers won't line up - but the visual idea is there.

Any help with this ggplot issue would be greatly appreciated.

Upvotes: 0

Views: 699

Answers (1)

kstew
kstew

Reputation: 1114

You can try this: add a row number, grouping by type, then use that to fill in each colour and stack the bars. You can then edit the colours and remove the legend.

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

enter image description here

UPDATE

Your overlay idea won't work perfectly, since you have duplicate values for Notification. See below -- arranging the data first by Notification then plotting achieves the solid colour overlay, but hides the fact that there are duplicates (whereas the stacked bar shows this).

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)))

enter image description here

Upvotes: 1

Related Questions