I want to plot a table as a stacked bar plot and label the bars with the percentages. Here is an example:
data <- matrix(c(34, 66, 22, 78), ncol = 2)
data <- as.table(data)
colnames(data) <- c("shop1", "shop2")
rownames(data) <- c("prod1", "prod2")
library(reshape2)
data_m <- melt(data, varnames = c("Product", "Shop"), id.vars = "Product")
library(scales)
library(ggplot2)
ggplot(data_m, aes(x = Shop, y = value, fill = Product)) +
geom_bar(position = "fill", stat = "identity") +
scale_y_continuous(labels = percent_format()) +
labs(x = "", y = "")
I tried to add the labels with
geom_text(data = data_m, aes(x = Shop, y = value,
label = paste0((value/100) * 100,"%")), size=4)
EDIT: With JanLauGe's answer I get
Now, the percentages are wrongly assigned.
Another remark: what to do if the column sums of the table were not the same, say 91 and 107 instead of 100 as assumed in my above example?