Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
853 views
in Technique[技术] by (71.8m points)

r - Showing percentage in bars in ggplot

I have a dataset with binary variables like the one below.

M4 = matrix(sample(1:2,20*5, replace=TRUE),20,5)
M4 <- as.data.frame(M4)
M4$id <- 1:20

I have produced a stacked bar plot using the code below

library(reshape)
library(ggplot2)
library(scales)
M5 <- melt(M4, id="id")
M5$value <- as.factor(M5$value)
ggplot(M5, aes(x = variable)) + geom_bar(aes(fill = value), position = 'fill') +
  scale_y_continuous(labels = percent_format())

Now I want the percentage for each field in each bar to be displayed in the graph, so that each bar reach 100%. I have tried 1, 2, 3 and several similar questions, but I can't find any example that fits my situation. How can I manage this task?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this method:

test <- ggplot(M5, aes(x = variable, fill = value, position = 'fill')) + 
  geom_bar() +
  scale_y_continuous(labels = percent_format()) +
  stat_bin(aes(label=paste("n = ",..count..)), vjust=1, geom="text")
test

enter image description here

EDITED: to give percentages and using the scales package:

require(scales)
test <- ggplot(M5, aes(x = variable, fill = value, position = 'fill')) + 
  geom_bar() +
  scale_y_continuous(labels = percent_format()) +
  stat_bin(aes(label = paste("n = ", scales::percent((..count..)/sum(..count..)))), vjust=1, geom="text")
test

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...