0

I am have a made a geom_col() chart in ggplot2 for which I would like to add labels on the bars, but only one per stacked bar. This is what my chart looks like without the labels:

gI <- df %>% 
  ggplot(aes(fill = Category, y=csum, x= tijdas)) +
  geom_col()
plot(gI)

enter image description here

And now comes the tricky part. Every stacked bar has is a specific Meeting_type and I would like to add this to the plot. I have tried adding

geom_text(aes(label = Meeting_Type), position = position_dodge(width=0.9), vjust=-0.25)

But this resulted in a label for every category within each bar (so a lot of text): enter image description here

I would like only one label per (stacked) bar that indicates the Meeting_type. Preferably in a readable place.

Slaatje
  • 127
  • 8

1 Answers1

1

Difficult to know the best approach without seeing your data, but it's possible that substituting geom_text for stat_summary would be a good way of summing each column to get the position of the label:

library(ggplot2)
library(dplyr)

mtcars %>% 
  ggplot(aes(factor(cyl), y = mpg, fill = factor(gear))) +
  geom_col() +
  stat_summary(aes(label = factor(cyl), fill = NULL),
               fun = sum, 
               geom = "text", vjust = -0.25)

Created on 2020-12-15 by the reprex package (v0.3.0)

As I say, may need a different function for your data - if this isn't a solution then do post a sample using dput and we'll see if we can make it work for your data.

Andy Baxter
  • 5,833
  • 1
  • 8
  • 22
  • Glad it helped! I've used several bad ways of trying to solve this problem in the past, but the `stat_summary` function that I've just recently started getting used to is really good for tidying/shortening code. – Andy Baxter Dec 15 '20 at 15:29