Christoffer R
Christoffer R

Reputation: 3

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?

Upvotes: 0

Views: 5975

Answers (3)

Tom Martens
Tom Martens

Reputation: 776

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

Upvotes: 0

Daniel
Daniel

Reputation: 7832

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...

Upvotes: 1

lawyeR
lawyeR

Reputation: 7654

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

Upvotes: 2

Related Questions