0

when I am using the following code, I get the percentage of 100% for each group. But I want it to be 100% overall. Each time should be as long as percentage-bar as they are represented in the whole variable.

So 20:00 (n=3) should account for 43%, 21:00 (n=2) for 29 % and so on.

DF <- data.frame(time = c("20:00", "22:00", "23:00", "21:00", "21:00", "20:00", "20:00"),
                 group = as.factor(c("early", "late", "late", "early", "early", "early", "early")))

library(ggplot2)
ggplot(data = DF, aes(x = time, y = stat(prop), fill = factor(..group..), group = group))+
  geom_bar()

How to do that? Thanks in advance!

Schillerlocke
  • 305
  • 1
  • 14

3 Answers3

2

stat(prop) calculates the proportion per group (see here and here). I couldn't make it work to set group = 1 but use another fill, so the easiest solution is to calculate the proportions beforehand and use geom_col:

DF <- data.frame(time = c("20:00", "22:00", "23:00", "21:00", "21:00", "20:00", "20:00"),
                 group = as.factor(c("early", "late", "late", "early", "early", "early", "early")))

library(dplyr)
DF_new <- DF %>% 
  group_by(time) %>% 
  summarise(percentage = n()) %>% 
  mutate(percentage = percentage / sum(percentage)) %>% 
  left_join(DF %>% distinct(), by = "time")

library(ggplot2)
ggplot(data = DF_new, aes(x = time, y = percentage, fill = group))+
  geom_col()

enter image description here

starja
  • 9,887
  • 1
  • 13
  • 28
2

Also this work:

ggplot(data = DF) +
  geom_bar(aes(time, y = stat(count)/sum(stat(count)), fill = group))
det
  • 5,013
  • 1
  • 8
  • 16
1
library(tidyverse)
DF <- data.frame(time = c("20:00", "22:00", "23:00", "21:00", "21:00", "20:00", "20:00"),
                 group = as.factor(c("early", "late", "late", "early", "early", "early", "early")))


df1 <- DF %>% 
    group_by(time) %>% summarise(n = n()) %>% mutate(percent = n/sum(n)*100)
df1 %>% ggplot(aes(x = time, y = percent))+geom_col(aes(fill = "red"))+
    geom_label(aes(label = percent))

enter image description here

Sri Sreshtan
  • 535
  • 3
  • 12