0

I am trying to add percentage label on bars of bar a plot. Now I only have numbers without the % symbol. I tried to do it with labels=percent and scales::label_percent() but they did not make it happen. I am sure there are similar questions to this on Stack, but I didn't find them among the suggested ones.

Code for the plot

ggplot(remove_missing(mydata), mapping = aes(x = value, y = pct)) +
  geom_col(aes(fill = value),
           width = 0.30) +
  scale_y_continuous(lim=c(0,1),labels=scales::percent) +
  geom_text(aes(label=100*round(pct,2)), colour="red", size=3) +
  scale_fill_manual(
    values = c('option1' = "blue", 
               'option2' = "blue", 
               'option3' = "blue",
               'option4' = "blue",
               'option5' = "blue",
               'option6' = "blue",
               'option7' = "blue",
               'option8' = "blue",
               'option9' = "blue",
               'option10' = "blue",
               'option11' = "blue",
               'option12' = "blue",
               'option13' = "blue"),
    drop = FALSE) +
  labs(x = "", y = "pct of responders") +
  guides(fill = "none") +
  theme(
    plot.margin = margin(t = 0, r =  30, b = 20, l = 5.5),
    plot.title = element_text(size = 15, face = "plain"),
    panel.background = element_blank(),
    panel.grid.major = element_line(colour = "grey"),
    #panel.grid.major.x = element_blank(),
    panel.grid.major.y = element_blank(),
    #panel.grid.minor = element_line(colour = "lightgrey"),
    axis.ticks.x = element_blank(),
    axis.ticks.y = element_line(colour = "grey"),
    axis.text.y = element_text(
      size = 11,
      face = "plain",
      hjust = 0
    ), 
    axis.text.x = element_text(
      size = 11,
      face = "plain",
      hjust = 0
    ),
    axis.title.x = element_text(size = 12),
  ) +
  coord_flip() +
  ggtitle("") +
  scale_x_discrete(labels = function(x)
    str_wrap(x, width = 20))
user438383
  • 5,716
  • 8
  • 28
  • 43
Gato
  • 389
  • 2
  • 12
  • Unfortunately Stack did not allow me to add the structure of the test data I had for this plot, because "too much code" – Gato Jan 20 '23 at 13:00
  • 1
    Try `geom_text(aes(label=scales::percent(pct, accuracy = .01))` – stefan Jan 20 '23 at 13:06
  • @stefan I already have ```geom_text(aes(label=100*round(pct,2)), colour="red", size=3)``` so there is different stuff after ```label=```, and I can't over write that with what you suggested – Gato Jan 20 '23 at 13:17
  • 1
    Do `geom_text(aes(label=scales::percent(pct, accuracy = .01)), colour="red", size=3)`. scales::percent will by default do 100*., add a %. and a accuracy = .01 means to round two 2 digits. – stefan Jan 20 '23 at 13:21

0 Answers0