我读了这篇关于 ggplot 显示 % 而不是计数的帖子,但是当我有一个由多个因子变量组成的融化数据框时,我无法让它工作。
这给了我一个图,其中条形图仍然显示计数,而不是我想要的 %。
# 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
提前致谢