-1

I have a data frame which is coded below

    Variable=c("ABC","ABC","MNO","MNO","XYZ","XYZ")
Flag=c("Y","N","Y","N","Y","N")
Count=c(1234,9876,6789,3210,5500,7890)
df<-cbind(Variable,Flag,Count)
df<-as.data.frame(df)

I want to plot a bar graph that will show basically the count and the percentage of Y and N for each group.I have done this until now

library(ggplot2)
ggplot(df, aes(x=Variable,fill=Flag))+ geom_bar(position = "dodge")+
  stat_count(aes(label=paste0(sprintf("%1.1f", ..count../sum(..count..)*100),
                              "%n", ..count..), y=1*..count..), 
             geom="text", colour="white", size=4, position=position_dodge(width=1)) 

This shows the count For percentage I have tried this

temp <- df %>% group_by( Variable, Flag) %>% 
  group_by(Variable) %>% mutate(percentage = 100*(Count/sum(Count)))

ggplot(temp, aes(x = Variable, fill = factor(Flag),y=percentage)) +
  geom_bar(stat = "identity", position = "dodge") +
  geom_text(aes(label = percent(percentage)), vjust = 0.5) +
  scale_y_continuous(labels = percent)

I don't now how to bring them together in one plot in R.

I want something as same as this to be produced Bar-chart that is needed

Prabhu
  • 87
  • 1
  • 10
  • 1
    Hi. This is one of the most commonly asked questions in this tag. see for example https://stackoverflow.com/questions/29869862/how-to-add-percentage-or-count-labels-above-percentage-bar-plot, or google your exact question and this is giving at least 20 results - please elaborate why those don't help you – tjebo Dec 07 '21 at 10:37
  • No, I have tried these and failed to add both at the same time. – Prabhu Dec 07 '21 at 10:39
  • Bro, I have tried many things and could not get the answer. That's why I used this platform. I need to add both at the same time where I am finding it difficult. – Prabhu Dec 07 '21 at 10:43
  • https://stackoverflow.com/questions/62158913/how-do-have-both-count-and-percent-on-barcharts-in-ggplot2-r – tjebo Dec 07 '21 at 10:44

2 Answers2

3
df <- mtcars

library(tidyverse)
fg <- df %>%
  count(cyl) %>%
  mutate(
    perc = round(proportions(n) * 100, 1),
    res = str_c(n, "(", perc, ")%"),
    cyl = as.factor(cyl)
    )

ggplot(fg, aes(cyl, n, fill = cyl)) +
  geom_col() +
  geom_text(aes(label = res), vjust = -0.5)

Created on 2021-12-07 by the reprex package (v2.0.1)

Yuriy Saraykin
  • 8,390
  • 1
  • 7
  • 14
0

One way to do it is by first creating a 'percent' variable, then plot wit geom_col and geom_text. We can paste0 "Count" and "percent" to have the desired labels.

library(dplyr)
library(ggplot)

df_for_plot<-df %>% group_by(Variable)%>%
    mutate(proportions = scales::percent(Count/sum(Count), 0.01))

df_for_plot %>% ggplot(aes(x = Variable, y = Count, fill = Flag)) +
    geom_col(position = 'dodge') +
    geom_text(aes(label=paste0(Count, '(', proportions, ')'))

enter image description here

GuedesBF
  • 8,409
  • 5
  • 19
  • 37