Showing percentage in bars in ggplot

2019-01-27 09:51发布

问题:

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?

回答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"))

Plot appearance can be custzomized with various parameters...



回答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

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



回答3:

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