Home > Mobile >  How to include a bar for "total" in a stacked bar chart for categorical variable in R
How to include a bar for "total" in a stacked bar chart for categorical variable in R

Time:03-17

I would like to include a bar for "total" in a stacked bar chart plotting a categorical variable. A simplified example of my problem looks like this:

I have 3 cities (London, Berlin, Vienna) and 2 Types of tourists. I can plot the share of tourists that come more than once (repeat) versus those who come only once (once) for each city using the code below.

Now, I would like to add a bar for the share repeat/once in general (not by city) in the same chart. Unfortunately, I could not find any hint on how to do this.

I would be really grateful for a hint how to add this "total bar" as I need it quite frequently. Thank you very much in advance!

df <- data.frame("City"=c("Vienna","Vienna","London","London","Berlin", "London", "Berlin","Berlin","Vienna","Vienna","Vienna", "Vienna", "Berlin","Vienna","Vienna","Vienna"),"Type"=c("repeat","once","repeat","once","repeat","once", "repeat","once","repeat","once","repeat","repeat","repeat","repeat","repeat","once"))


df %>% 
  ggplot(aes(x=City, fill=Type), reorder(Type))   
  geom_bar(position="fill", alpha=0.75)  
  scale_fill_brewer(palette = "Paired")   
  coord_flip()


´´´

CodePudding user response:

You could achieve your desired result by adding a second geom_bar where you map a constant (e.g. the string Total) on x and setting the order of categoreis via scale_x_discrete:

library(ggplot2)

ggplot(df, aes(x=City, fill=Type), reorder(Type))   
  geom_bar(position="fill", alpha=0.75)  
  geom_bar(aes(x = "Total"), position="fill", alpha=0.75)  
  scale_fill_brewer(palette = "Paired")   
  scale_x_discrete(limits = c("Total", unique(df$City)))  
  coord_flip()

  • Related