Danny
Danny

Reputation: 574

Adding points to stacked barplot based on conditions in ggplot

I have a stacked bar plot which shows the frequency of size distributions of different kinds of buildings across several companies.

I am replicating this chart for each company in the dataset and for each company would like to add a dot in the stacks that represent the sizes of the buildings in their company. I was able to set up bar chart and add points to the graph. However, I’m unable to figure out how to place the dots in the correct places.

Here’s my code:

Data<-data.frame(Location = c("HQ", "Plant", "Warehouse", "Office", "HQ","Plant",
                              "Warehouse","Office","HQ","Plant","Warehouse","Office"),
                 Company=c("a","a","a","a","b","b","b","b","c","c","c","c"),
                 Staff=c("Small","Medium","Large","Medium","Small","Medium","Medium","Large","Large","Large","Small","Small"))

ggplot(Data,aes(x=Location,fill=Staff))+
  geom_bar(position = 'fill')+
  geom_point(aes(y = stat(..count../sum(..count..)),
                 color = Staff), stat = 'count',
             position = position_fill(0.5), size = 5)+  
  scale_color_manual(values = 'black', limits = "Medium")

Here’s what I have so far.

Current

I would like to figure out how to do this for company "a" so the chart looks something like this:

Desired

I’m thinking to start I would need to create a vector that shows the staff bins for that company: Point<-as.character(Data$Staff[Data$Company=="a"])

Upvotes: 2

Views: 966

Answers (1)

Z.Lin
Z.Lin

Reputation: 29085

The following should fit your requirements. (I've also wrapped it in a function for convenience in switching between companies.)

library(dplyr)

show.company.point <- function(company.name) {
  p <- ggplot(Data,
              aes(x = Location, fill = Staff))+
    geom_bar(position = 'fill')+
    geom_point(data = . %>%
                 mutate(alpha = Company == company.name) %>% 
                 group_by(Location, Staff) %>%
                 summarise(n = n(),
                           alpha = any(alpha)) %>%
                 ungroup(),
               aes(y = n, alpha = alpha, group = Staff),
               position = position_fill(0.5, reverse = F),
               size = 5, show.legend = F) +
    ggtitle(paste("Company", company.name)) +
    scale_alpha_identity()
  return(p)
}

show.company.point("a")
show.company.point("b")
show.company.point("c")

results

Upvotes: 1

Related Questions