Search code examples
rggplot2labelgeom-text

Creat data label for geom_count


I am really new to R, and I am now practicing making data visualizations with the "palmerpenguins" package: I have made the following plot to check the distributions of penguins based on their species and islands:

ggplot(data=penguins_raw,mapping=aes(x=Species,y=Island))+
  geom_count(aes(color=after_stat(n)))

enter image description here

However, I would also like to add the data labels to show the count of penguins of each species/island. I understood that I should use the "geom_text" function, but I have tried but could not write the function correctly. Really appreciate your help!

The functions I have tried include: #1:

ggplot(data=penguins_raw,mapping=aes(x=Species,y=Island))+
  geom_count(aes(color=after_stat(n)))+
  geom_text(aes(label=n,color = "#ffffff"))

#2:

ggplot(data=penguins_raw,mapping=aes(x=Species,y=Island))+
  geom_count(aes(color=after_stat(n)))+
  geom_text(aes(label=after_stat(n),color = "#ffffff"))

but obviously I am not writting the correct function.


Solution

  • The issue is that geom_count uses stat="sum" under the hood to compute the "counts", whereas the stat defaults to "identity" for geom_text. Instead, if you want to add the counts displayed by geom_count to your chart you have use stat="sum" for geom_text too. Only then can you use after_stat to display the counts as labels:

    library(ggplot2)
    library(palmerpenguins)
    
    ggplot(data = penguins_raw, mapping = aes(x = Species, y = Island)) +
      geom_count(aes(color = after_stat(n))) +
      geom_text(aes(label = after_stat(n)),
        color = "#ffffff",
        stat = "sum"
      )