add percentage in ggplot2

hi, I want to add percentage in the bar plot. How can I do for it?
thank you.
this is my code. thank you.

library(ggplot2)
df2 <- data.frame(classify=rep(c("AB", "C1","C2","DE"), each=7),
                  type=rep(c("No_religion", "Christian", "Buddhist","Hindu","Jewish","Muslim","Sikh"),4),
                  num=c(22115,47909,453,1882,709,2391,646,39435,96496,800,2446,824,6334,1205,
                        19107,51339,326,597,131,2025,465,25921,78338,523,1529,293,7072,985))
head(df2)
win.graph(width=4.875,height=3,pointsize=8)
ggplot(data=df2, aes(x=type, y=num, fill=classify)) +
   geom_bar(stat="identity", position=position_dodge())+
   geom_text(aes(label=num), vjust=-0.3, color="black",
             position = position_dodge(0.9), size=4.4)+
   scale_fill_brewer(palette="Paired")+
   theme_minimal()

If you want to put both the percentage within each group and the absolute count you can use the following code.

library(ggplot2)
library(dplyr,warn.conflicts = FALSE)
df2 <- data.frame(classify=rep(c("AB", "C1","C2","DE"), each=7),
                  type=rep(c("No_religion", "Christian", "Buddhist","Hindu","Jewish","Muslim","Sikh"),4),
                  num=c(22115,47909,453,1882,709,2391,646,39435,96496,800,2446,824,6334,1205,
                        19107,51339,326,597,131,2025,465,25921,78338,523,1529,293,7072,985))
df2 <- df2 %>% group_by(type) %>%  mutate(N = sum(num), Perc = paste(round(num/N * 100,1),"%"))
head(df2)
win.graph(width=4.875,height=3,pointsize=8)
ggplot(data=df2, aes(x=type, y=num, fill=classify)) +
  geom_bar(stat="identity", position=position_dodge())+
  geom_text(aes(label=num), vjust=-0.3, color="black",
            position = position_dodge(0.9), size=4.4)+
  geom_text(aes(y = num + 10000, label=Perc), vjust=-0.3, color="black",
            position = position_dodge(0.9), size=2) +
  scale_fill_brewer(palette="Paired")+
  theme_minimal()
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.