Search code examples
rggplot2bar-chartgeom-text

Not all Counts Appearing with geom_text


I have a data set of several features of several organisms. I'm displaying each feature individually by several different categories individually and in combination (e.g. species, location, population). Both in raw counts and a percentage of the total sample size and a percentage within a give group.

My problem comes when I'm trying to display a stacked bar chart using ggplot for the percent of individuals within a group. Since the groups do not have the same number of individuals in them, I'd like to display the raw number or count of individuals with that feature on their respective bars for context. I've managed to properly display the stacked percentage bar chat and get the number of individuals from the most populous groups to display. I'm having trouble displaying the rest of the groups.

ggplot(data=All.k6,aes(x=Second.Dorsal))+
  geom_bar(aes(fill=Species),position="fill")+
  scale_y_continuous(labels=scales::percent)+
  labs(x="Number of Second Dorsal Spines",y="Percentage of Individuals within Species",title="Second Dorsal Spines")+
  geom_text(aes(label=..count..),stat='count',position=position_fill(vjust=0.5))

enter image description here


Solution

  • You need to include a group= aesthetic so that position_fill knows how to position things. In geom_bar, you set the fill= aesthetic, so ggplot assumed you also want to group by that aesthetic. In geom_text it assumes the group is your x= aesthetic. In your case, just add group=Species after your label= aesthetic. Here's an example:

    # sample dataset
    set.seed(1234)
    types <- data.frame(
      x=c('A','A','A','B','B','B','C','C','C'),
      x1=rep(c('aa','bb','cc'),3)
    )
    df <- rbind(types[sample(1:9,50,replace=TRUE),])
    

    Plot without grouping:

    ggplot(df, aes(x=x)) +
      geom_bar(aes(fill=x1),position='fill') +
      scale_y_continuous(label=scales::percent) +
      geom_text(aes(label=..count..),stat='count',
        position=position_fill(vjust=0.5))
    

    enter image description here

    Plot with group= aesthetic:

    ggplot(df, aes(x=x)) +
      geom_bar(aes(fill=x1),position='fill') +
      scale_y_continuous(label=scales::percent) +
      geom_text(aes(label=..count..,group=x1),stat='count',
        position=position_fill(vjust=0.5))
    

    enter image description here