rggplot2labelbar-chartpercentage

how to add percentage sign on bars in GGplot2


I searched SO quite a long time, but no hint helped me, so i am gonna ask seperately. I am a beginner in R and wrote following code:

matchplayerNew <- match_player %>% group_by(civ, group = winner) %>%
  summarize(count = n()) %>%  # count records by winner
  mutate(pct = count/sum(count))  # find percent of total

ggplot(matchplayerNew, aes(civ, pct, fill = group)) + 
  geom_bar(stat = "identity") + 
  geom_text(aes(label = sprintf("%0.2f", round((pct*100), digits = 2))), position = position_stack(vjust = .5), angle = 90) +
  scale_y_continuous(labels = percent) + 
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1, size = 13)) +
  scale_fill_manual("legend", values = c("Loose" = "royalblue3", "Win" = "darkorange2"))

and this gives me the following plot:

Plot image

I would now like to add the percentage sign in each bar and colour. Any suggestions?

Thanks in advance


Solution

  • Have you tried:

    geom_text(aes(label = percent (sprintf("%0.2f", round((pct*100), digits = 2))))
    

    Uses scales::percent to do it.

    Or

    geom_text(aes(label = paste0( sprintf("%0.2f", round((pct*100), digits = 2))), "%")
    

    Pastes a % to the end of the label

    Or

    geom_text(aes(label = sprintf("%0.2f%%", round((pct*100), digits = 2)))
    

    %% in sprintf inserts the text