I read this post about ggplot showing % instead of counts, but I cannot get it to work when I have a melted dataframe consisting of several factor variables.
This gives me a plot where the bars are still showing counts and not % as I were going for.
# Data
head(sabat)
V1 V2 V3 V4 V5 V6 V7 V8
1 2 2 2 2 2 2 1 2
2 2 1 2 1 2 1 1 2
3 2 2 2 2 2 2 2 1
4 1 2 2 2 2 2 2 2
5 2 1 2 2 2 2 1 2
6 2 1 2 1 2 1 1 2
# melt data.frame
sabat.m <- melt(sabat)
# set 2 to NA because as only want to plot the yes answers (1=yes, 2=no)
sabat.m$value[sabat.m$value==2] <- NA
sabat.m <- na.omit(sabat.m)
# Factor it
sabat.m$value <- factor(sabat.m$value)
#structure of the melted data.frame
str(sabat.m)
data.frame': 1020 obs. of 2 variables:
$ variable: Factor w/ 8 levels "V1","V2","V3",..: 1 1 1 1 1 1 1 1 1 1 ...
$ value : Factor w/ 1 level "1": 1 1 1 1 1 1 1 1 1 1 ...
- attr(*, "na.action")=Class 'omit' Named int [1:2412] 1 2 3 5 6 7 8 10 11 12 ...
.. ..- attr(*, "names")= chr [1:2412] "1" "2" "3" "5" ...
# Plot it
p <- ggplot(sabat.m, aes(x = variable)) +
geom_bar(aes(y = (..count..)/sum(..count..)), binwidth = 25) +
scale_y_continuous(labels = percent_format()) +
coord_flip()
p
Thanks in advance