Search code examples
rggplot2geom-bar

How to put in bar plot percent (%) with 2 digits with ggplot?


I don't have a lot of skills in R and I have two questions. Someone can help me with this?

a) I would like to put percent numbers in this graphic with two digits like (120,07%). I've been trying to do with "dplyr" but I can't do it.

b )So, Could I change the "y axe" with percent in the graphic?

Thanks!

library(ggplot2)
ggplot(place, aes(x = Place, y = Dif)) +
  geom_bar(aes(fill = Dif < 0), colour="black", stat = "identity") +
  scale_fill_manual(guide = FALSE, breaks = c(TRUE, FALSE), values=c("gray", "red")) +
  geom_text(aes(label=Dif), position=position_dodge(width=0.9), vjust=-0.25)
structure(list(Place = c("Supermarket", "Markets", 
"House", "Consumption", "Hipermarkets", "Comerce", 
"Outdoors sale"), Dif = c(-20.1884514229122, -50.0150282227513, 
5.34342366569214, -2.47231788994851, 25.7466309314144, 120.078289871755, 
24.0501027574048)), row.names = c(NA, -7L), class = c("tbl_df", 
"tbl", "data.frame"))

enter image description here


Solution

  • You could do:

    library(ggplot)
    
    ggplot(df, aes(Place, Dif/100, fill = Dif > 0)) + 
      geom_col() +
      geom_text(aes(y = Dif/100 + 0.1 * sign(Dif/100),
                    label = scales::percent(Dif/100))) +
      geom_hline(yintercept = 0) +
      scale_fill_manual(values = c("red", "forestgreen"), guide = guide_none()) +
      scale_y_continuous(labels = scales::percent, name = "Diff") +
      theme_bw()
    

    enter image description here