0
votes

I want to create a stacked barplot with two variables namely niveau en vak whereby vak is presented on the x axis and niveau is shown as two stacked bars (with different colors). At this moment I only have the plot where the y-axis contains count but I want to change it to percentage. It would be very nice if the percentages are presented with in the bars so it become clear how many times a specific values appears in the dataset.

vakken <- ggplot(data=etadam, aes(x = vak, fill = niveau)) + geom_bar(stat="count", width = 0.85 , position = 'dodge') + scale_fill_manual(values = c('#ffd308', 'black')) + geom_text(stat='count', aes(label=..count..), vjust=1.4, colour = "white", size = 4, position = position_dodge(0.8)) + labs(x = NULL, y = 'aantallen', title = 'Vak per niveau', subtitle = 'N = 400 | alle trainingen', caption = 'Leren voor de Toekomst ©')

data

ID                tijd                    gevoel waardevol        vak niveau vertrouwen    uitleg
1 90 2021-04-25 15:16:11        VrolijkGemotiveerd        Ja     Engels   HAVO         Ja Zeer goed
2 91 2021-04-25 15:17:08 RelaxtGemotiveerd Vrolijk        Ja     Engels   HAVO         Ja Zeer goed
3 92 2021-04-25 15:49:16                  Neutraal        Ja Wiskunde A   HAVO         Ja Zeer goed
4 93 2021-04-25 15:49:00             TrotsGezegend        Ja Wiskunde A   HAVO         Ja   Normaal
5 94 2021-04-25 15:49:03                  Neutraal        Ja Wiskunde A   HAVO        Nee Kan beter
6 95 2021-04-25 15:49:23                  Neutraal        Ja Wiskunde A   HAVO         Ja      Goed
1

1 Answers

0
votes

Is this what you were looking for?

df <- data.frame(vak = c("Engels", "Engels", "Wiskunde A", "Wiskunde A", "Wiskunde A", "Wiskunde A"), niveau = rep("HAVO", 6))
df.prop <- reshape2::melt(prop.table(table(df$vak, df$niveau), margin = 2))
df.prop$value <- round(df.prop$value * 100, 2)
ggplot(df.prop, aes(x = Var1, y = value)) + 
    geom_bar(stat = 'identity', fill = c('#ffd308', 'black')) + 
    geom_text(aes(label = value), vjust=1.4, colour = "white", size = 4, position = position_dodge(0.8)) + 
    labs(x = NULL, y = 'aantallen', title = 'Vak per niveau', subtitle = 'N = 400 | alle trainingen', caption = 'Leren voor de Toekomst ©')

enter image description here