0

I try to make a geom_bar figure and now I want the percentages by the bars. They are there, but not on the good place... Does anybody know how to fix that?

  filter(D=="D") %>%
  group_by(Operatiejaar, Ligging_compleet) %>%
  summarise(cnt = n()) %>%
  mutate(Percentage = formattable::percent(cnt / sum(cnt)))

ggplot(data=Data) +
  aes(x=Operatiejaar, y=cnt, fill=Ligging_compleet, group = Operatiejaar) +
  geom_bar(stat = "identity", width = 0.9, position = "dodge2") +
  ggtitle(
    label = "Ligging",
    subtitle = "Verhoudingen") +
  theme(
    plot.title = element_text(hjust = 0.5),
    plot.subtitle = element_text(hjust = 0.5)) +
  xlab("Jaar") +
  ylab("Aantallen") +
  labs(fill = "Ligging") +
  geom_text(
    aes(label = Percentage, group = Operatiejaar), 
    color = "dark grey", 
    position = position_dodge(width = 1),
    vjust = -0.5,
    hjust = 0,
    size = 3,
    angle = 90)

Now, the figure likes this: enter image description here

The two things I prefer:

  • Percentages above every bar
  • Percentages round on zero decimals instead of the 2 decimals now
Yvonne
  • 21
  • 3
  • 1
    1) You can specify the number of decimal places as `Percentage = formattable::percent(cnt / sum(cnt), digits = 0)` 2) In `geom_text` use `position = position_dodge2(width = 0.9)` – Seth Apr 25 '23 at 13:49

1 Answers1

0

Ths should work. Also take a look here:Position geom_text on dodged barplot

library(tidyverse)

set.seed(123)
values <- sample(1:100, 100, replace=T)
name <- rep(LETTERS[1:4], 25)
year <- rep(c("2018", "2019"), 50)

df <- tibble(name, values, year)

df %>%
  group_by(name, year) %>%
  summarise(sum=sum(values)) %>%
  ungroup %>%
  mutate(perc= round(sum/sum(sum), digits = 2)*100) %>%
  ggplot(aes(x=year, y=perc, fill=name))+
  geom_col(position = "dodge")+
  geom_text(aes(label= paste0(perc, "%")), vjust=-0.3, 
            position = position_dodge(width = 0.9))
#> `summarise()` has grouped output by 'name'. You can override using the
#> `.groups` argument.

Created on 2023-04-25 with reprex v2.0.2

Nick Glättli
  • 421
  • 1
  • 7