0

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?

Community
  • 1
  • 1

3 Answers3

2

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

lawyeR
  • 7,488
  • 5
  • 33
  • 63
  • That doesn't look like precentage to me, you probably want something like `paste(round((..count..)/sum(..count..)*100), "%")` (instead of `paste("n = ",..count..)`) – David Arenburg Sep 02 '14 at 10:06
  • Many thanks for your help! Worked out beautifully to get the counts, but I was looking for the percentage; perhaps you can give some advice on that? Would be immensely appreciated. – Christoffer R Sep 02 '14 at 10:08
  • @Arenburg: That code returns the cumulative percentage for the entire graph, instead of each bar. In other words, all the fields in all bars together add up to 100%, while I need each bar to add up to 100%. – Christoffer R Sep 02 '14 at 10:24
1

You could use the sjp.stackfrq function from the sjPlot-package (see examples here).

M4 = matrix(sample(1:2,20*5, replace=TRUE),20,5)
M4 <- as.data.frame(M4)
sjp.stackfrq(M4)
# alternative colors: sjp.stackfrq(M4, barColor = c("aquamarine4", "brown3"))

enter image description here

Plot appearance can be custzomized with various parameters...

Daniel
  • 7,252
  • 6
  • 26
  • 38
0

I really like the usage of the implicit information that is created by ggplot itself, as described in this post:

using the ggplot_build() function

From my point of view this provides a lot of opportunities to finally control the appearance of a ggplot chart.

Hope this helps somehow

Tom

Community
  • 1
  • 1
Tom Martens
  • 746
  • 9
  • 18